开发者

Testing a C++ library with Python

开发者 https://www.devze.com 2023-03-12 14:15 出处:网络
I have a libfoo.so library built from C++ code (compiled with gcc), and I would like to quickly test some of its exported classes (basically, instantiating a class then calling its methods to check th

I have a libfoo.so library built from C++ code (compiled with gcc), and I would like to quickly test some of its exported classes (basically, instantiating a class then calling its methods to check the output).

While I could do开发者_JS百科 that in C/C++ with a main file that links to the library in question and build my tests, but I think it would be much easier if it was possible to simply call Python from the command line and call the methods from there.

I know I can use CDLL from ctypes to load C-style libraries, but is there a similar functionality for C++ libraries and objects?

EDIT : Ideally, I do not want to modify the C++ code, I would need to use it as-is.


Honestly C++ is a bit messy. You could do something like create a pure C function which wraps the C++ functionality (which you then call from python) but at that point you might as well write your tests in C++. Unfortunately the only tool out there for this (that I know of) is SWIG.

It's sad that it's called the "simplified" wrapper and interface generator, because there's nothing simple about it. If you have VERY primitive data types in your signatures (like, JUST ints or maybe char*) it'll be a pretty quick job. Otherwise you have to tell swig how to marshal your data types between languages, and that gets REALLY ugly very quickly. Furthermore, after short time you realize you have to learn the CPython API in order to write your marshalling code.

And by that point you may as well write your own CPython wrapper without involving SWIG. You suddenly realize you've spent a good month learning a new API and feel horribly frustrated. If you're going to be doing this a lot, it's definitely worth your time. However if this is a one-time thing, just write your tests in C / C++.

(I'm speaking from experience here)


I agree with Chris answer. However, I want to point out that Cython supports C++ (with some limitations).

0

精彩评论

暂无评论...
验证码 换一张
取 消