Cython: How to wrap a C++ function that returns a C++ object?

I'm working on a Python project where I'd like to interface with a C++ package that has already been written. Since I'll be using Cython in other portions of this project, I'd prefer to wrap using Cython.

In brief, I need to wrap a function, FooBar, that returns an object of custom class type Bar.

2.) Independent of this error, is this even the right approach to what I want to do? For reference, if I just tried to wrap the class by itself I have had no problem: I can import the module, create objects using PyBar(), and underlying C methods implemented on the class would work. The issue is trying to wrap a function that returns objects of the C++ class. In the wild, I'll never actually want to create PyBar representation of any Bar object that wasn't created by FooBar, so this is the approach I decided upon after much head scratching.

Best How To :

With respect to the first part of the problem, I think the more elegant change would be to have FooBar defined as:

Bar* FooBar(const std::vector<double> & O, size_t P, size_t Q);

and have it return a "new" allocated pointer. I think in your original Cython code __cinit__ you'll create a stack allocated Bar, take a pointer of that, and then that will expire resulting in eventual disaster.

An alternative solution that might work would be be to keep FooBar returning Bar, change PyBar so it starts

You can do this without recursion by simply expanding the parameter pack directly into a std::tuple: template<My_enum... Enums> struct Tuple { using type = std::tuple<typename Bind_type<Enums>::type...>; }; To answer your question more directly, you can declare a variadic primary template, then write two specializations: for when there are at least...

If you want the None and '' values to appear last, you can have your key function return a tuple, so the list is sorted by the natural order of that tuple. The tuple has the form (is_none, is_empty, value); this way, the tuple for a None value will be...

Make sure you have set properly with ~/.boto and connect to aws, have the boto module ready in python. If not, go through this first: Getting Started with Boto For example, you need assign a new EIP 54.12.23.34 to the instance i-12345678 Make sure, EIP has been allocated(existed) and you...

You can create a set holding the different IDs and then compare the size of that set to the total number of quests. The difference tells you how many IDs are duplicated. Same for names. Something like this (untested): def test_quests(quests): num_total = len(quests) different_ids = len(set((q.ID for q in...

Twilio developer evangelist here. Twilio Client uses WebRTC and falls back to Flash in order to make web browsers into phones. Unfortunately Safari on iOS supports neither WebRTC nor Flash so Twilio Client cannot work within any browser on iOS. It is possible to build an iOS application to use...

To count how often one value occurs and at the same time you want to select those values, you'd simply select those values and count how many you selected: fruits = [f for f in foods if f[0] == 'fruit'] fruit_count = len(fruits) If you need to do this for...

Your error is actually coming from: array.push_back(day); This tries to put a copy of day in the vector, which is not permitted since it is unique. Instead you could write array.push_back( std::move(day) ); however the following would be better, replacing auto day...: array.emplace_back(); ...

if you only need to do this for a handful of points, you could do something like this. If intensites and radius are numpy arrays of your data: bin_width = 0.1 # Depending on how narrow you want your bins def get_avg(rad): average_intensity = intensities[(radius>=rad-bin_width/2.) & (radius<rad+bin_width/2.)].mean() return average_intensities #...

I don't know what you are exactly trying to achieve but if you are trying to count R and K in the string there are more elegant ways to achieve it. But for your reference I had modified your code. N = int(raw_input()) s = [] for i in range(N):...

Your list contains one dictionary you can access the data inside like this : >>> yourlist[0]["popularity"] 2354 [0] for the first item in the list (the dictionary). ["popularity"] to get the value associated to the key 'popularity' in the dictionary....

The main reason to do something like this is to specialize void integerA(int x) to do something else. That is, if the programmer provides as input argument an int to member function abc::integerA then because of the C++ rules instead of instantiating the template member function the compiler would pick...

Insert only accepts a final document or an array of documents, and an optional object which contains additional options for the collection. db.collection.insert( <document or array of documents>, { // options writeConcern: <document>, ordered: <boolean> } ) You may want to add the _id to the document in advance, but...

You could use std::promise and std::future (or their boost counterparts if your are not yet on C++11). The idea is to store a std::shared_ptr<std::promise<bool>> with the current sequence id as a key in the map whenever a request is sent. In the blocking send function you wait for the corresponding...

Short answer: your correct doesn't work. Long answer: The binary floating-point formats in ubiquitous use in modern computers and programming languages cannot represent most numbers like 0.1, just like no terminating decimal representation can represent 1/3. Instead, when you write 0.1 in your source code, Python automatically translates this to...

First off, it might not be good to just go by recall alone. You can simply achieve a recall of 100% by classifying everything as the positive class. I usually suggest using AUC for selecting parameters, and then finding a threshold for the operating point (say a given precision level)...

These integers are handles.This is a common idiom used by many APIs, used to hide resource access through an opaque level of indirection. OpenGL is effectively preventing you from accessing what lies behind the handle without using the API calls. From Wikipedia: In computer programming, a handle is an abstract...

I think the problem is with your start.py file. You have a function refreshgui which re imports start.py import will run every part of the code in the file. It is customary to wrap the main functionality in an ''if __name__ == '__main__': to prevent code from being run on...

Change this: [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 36)] private string iu; to this: [MarshalAs(UnmanagedType.LPStr)] private string iu; Note that this code is good only to pass a string in the C#->C++ direction. For the opposite direction (C++->C#) it is more complex, because C# can't easily deallocate C++ allocated memory. Other important thing:...

Section 21.4.1.5 of the 2011 standard states: The char-like objects in a basic_string object shall be stored contiguously. That is, for any basic_string object s, the identity &*(s.begin() + n) == &*s.begin() + n shall hold for all values of n such that 0 <= n < s.size(). The two...

Use stoi, it's the modern C++ version of C's atoi. Update: Since the original answer text above the question was amended with the following error message: ‘stoi’ was not declared in this scope Assuming this error was produced by g++ (which uses that wording), this can have two different causes:...

You might want to have a look at Tornado. It is well-documented and features built-in support for WebSockets. If you want to steer clear of the Tornado-framework, there are several Python implementations of Socket.io. Good luck!...

Your program is not ill-formed because <vector> is guaranteed to include <initializer_list> (the same is true for all standard library containers) §23.3.1 [sequences.general] Header <vector> synopsis #include <initializer_list> ... Searching the standard for #include <initializer_list> reveals the header is included along with the following headers <utility> <string> <array> <deque> <forward_list>...

Your issue is that std::deque (and other standard containers) doesn't just take a single template argument. As well as the stored type, you can specify an allocator functor type to use. If you don't care about these additional arguments, you can just take a variadic template template and be on...

By default variables are string in Robot. So your first two statements are assigning strings like "xx,yy" to your vars. Then "evaluate" just execute your statement as Python would do. So, adding your two strings with commas will produce a list: $ python >>> 1,2+3,4 (1, 5, 4) So you...

The convention is to declare constants in modules as variables written in upper-case (Python style guide: https://www.python.org/dev/peps/pep-0008/#global-variable-names). But there's no way to prevent someone else to re-declare such a variable -- thus ignoring conventions -- when importing a module. There are two ways of working around this when importing modules...

You need to read one bite per iteration, analyze it and then write to another file or to sys.stdout. Try this code: mesh = open("file.mesh", "r") mesh_out = open("file-1.mesh", "w") c = mesh.read(1) if c: mesh_out.write("{") else: exit(0) while True: c = mesh.read(1) if c == "": break if c...

Afraid I don't know much about python, but I can probably help you with the algorithm. The encoding process repeats the following: multiply the current total by 17 add a value (a = 1, b = 2, ..., z = 26) for the next letter to the total So at...

Removing BreakBeforeBraces: Allman Seems to do what you want (for me). I'm using SVN clang though. Although you probably wanted it there for a reason. According to the clang-format docs, the AllowShortBlocksOnASingleLine should do exactly what you want (regardless of brace style). This might be a bug in clang-format....

The pipeline calls transform on the preprocessing and feature selection steps if you call pl.predict. That means that the features selected in training will be selected from the test data (the only thing that makes sense here). It is unclear what you mean by "apply" here. Nothing new will be...

The valid range of indices of an array with N elements is [0, N-1]. Thus instead of for example this loop for (int i=1; i <= n; i++) ^^^^ ^^^^^^ you have to write for ( int i = 0; i < n; i++ ) As you used operator new...

If you want a sequence of int, then use a vector<int>. Using the key_char string, the values of the chars in it will serve as the initial value of the ints. std::vector<int> key_num(key_char.begin(), key_char.end()); Then, iterate over each character of key_num and convert it to the equivalent int value for...

You can use the include tag in order to supply the included template with a consistent variable name: For example: parent.html <div class="row"> <div class="col-md-12 col-lg-12 block block-color-1"> {% include 'templates/child.html' with list_item=mylist.0 t=50 only %} </div> </div> child.html {{ list_item.text|truncatewords:t }} UPDATE: As spectras recommended, you can use the...

a. It's a left shift: https://docs.python.org/2/reference/expressions.html#shifting-operations It shifts the bits one to the left. b. Note that ^ is not the "to the power of" but "bitwise XOR" in Python. c. As the comment states: it defines "number of bits per signature" as 2**10 → 1024 d. The lines calculate...

If this is interview question or something , and you have to do it anyways , you can do this like ,below code . derive from std::stack , and overload [] operator #include <iostream> #include <algorithm> #include <stack> #include <exception> #include <stdexcept> template <typename T> class myStack:public std::stack<T> { public:...

According to documentation of numpy.reshape , it returns a new array object with the new shape specified by the parameters (given that, with the new shape, the amount of elements in the array remain unchanged) , without changing the shape of the original object, so when you are calling the...

Speaking as someone who's had to do exactly what you're talking about a number of time, rr got it basically right, but I would change the emphasis a little. For file versioning, text is basically the winner. Since you're using an hdf5 library, I assume both serializing and parsing are...

This map: typedef map<string, Object> obj_map; only stores Object objects. When you try to put an Image in, it is sliced down and you lose everything in the Image that was not actually part of Object. The behaviour that you seem to be looking for is called polymorphism. To activate...