I have a class with few methods and I'm happy with the performance of all of them except one method. We want to port that to C++. However we don't want to spend too much time porting the whole class to C++, just that single method. Is this possible? How should I do it? Should it be in a blank class? Not in a class? What I want is to try to use the C version and if failed (other OS, missing pyd), load the Python version. Thank you.
Asked
Active
Viewed 160 times
2
-
do other methods in the class use the method that you want to port? – Foo Bah Oct 02 '11 at 05:15
-
Why C++? Why not just C? – Chris Lutz Oct 02 '11 at 05:18
-
@Chris Lutz: Because C++ is C + 1! – GWW Oct 02 '11 at 05:19
-
yes other methods call the method – Oct 02 '11 at 05:44
-
@Chris Lutz: because I'm porting a method, as far as I know C doesn't even support OOP. – Oct 02 '11 at 05:45
-
3You might consider publishing this slow method -- it's quite possible that it could be (a) sped up while remaining written in Python (b) not worth the effort of (trying to) get it going in C. – John Machin Oct 02 '11 at 05:45
-
2A class method is just a function whose first arg is a pointer to an instance of that class. C++ has its own OOP model, which you will not be using. – John Machin Oct 02 '11 at 05:49
-
Most definitely not an option. Is it possible or not? And how would you do it? – Oct 02 '11 at 05:55
-
What is most definitely not an option??? – John Machin Oct 02 '11 at 06:29
-
Yes, it's not an option. I wouldn't make this thread if it was. Are you actually surprised that there can be case where performance matters? – Oct 02 '11 at 06:43
-
@user975135 - Python is written in C, yet it supports methods. Assembly doesn't have methods, yet C++ compiles down to that. At some level, methods are just function calls. Python can easily be extended with C, and that's the most common language to use with Python (other than Python itself) because of ABI compatability. – Chris Lutz Oct 02 '11 at 17:08
-
if you can specify that a function should behave as a method when called from Python, then I rest my case. But still, my question isn't answered :( (my original post and reply to GWW) – Oct 02 '11 at 18:08
1 Answers
1
Depending on the complexity of your code, you could look into using Weave, which is part of SciPy. It allows you to embed C/C++ code in your python module. There's a tutorial here.
Another option you could look at is Boost::Python, which may be a bit more complex to use.

GWW
- 43,129
- 11
- 115
- 108
-
still waiting for an answer. The question is could (should) you make a method for a Python class in C++. If yes, how? If no, how would you do it then? And how could you tell in your code to run the pyton version if it fails (other OS, missing pyd). – Oct 02 '11 at 13:03