Python importing & using cdll (with a linux .so file)

浪尽此生 提交于 2019-12-24 08:47:29

问题


After one of my last questions about python&c++ integration i was told to use dlls at windows. (Previous question)

That worked ok doing:

cl /LD A.cpp B.cpp C.pp

in windows enviroment, after setting the include path for boost, cryptopp sources and cryptopp libraries.

Now i'm tryting to do the same in linux, creating a .so file to import through ctypes on python2.5. I did:

gcc -Wall -Wextra -pedantic A.cpp B.cpp C.cpp /usr/lib/libcryptopp.so -shared -o /test/decoding.so

and the so object is created ok. If removed "-shared" compilation is OK but stops as no main in there (obviously ;) ). Of course libcryptopp.so exists too.

But when i go to python and import the "so" file, it said that the attribute has no object "decrypt", "encrypt" or whatever i put there. using "dir" over the dll objects confirms that they are not there.

external functions are defined in A.cpp as:

int encrypt (params...)
//..
return num;

int decrypt (params...)
//..
return num;

also tried using:

extern "C" encrypt (params...)
.....

Could anyone tell me what i'm doing wrong?

Thanks in advance!

Rag


回答1:


C++ compiler mangles names of functions. To do what you are trying to do you must have the declaration prototype inside

extern "C" {...}

it's hard to tell from your samples what exactly you have in a source file. As someone already mentioned, use nm utility to see what objects that are in your shared object.

Do not compile your object without -shared. Python load library does not support statically linked objects as far as am aware.

compile your object with g++ compiler instead, it will link to standard C++ Library, gcc does not.




回答2:


just to doublecheck something since you using boost.

#include <string>
#include <boost/python.hpp>
using namespace std;

string hello(string s){
    return "Hello World!";
}

BOOST_PYTHON_MODULE(pyhello){
    using namespace boost::python;

    def("hello", hello);
}

in python

>>> import pyhello
>>> print pyhello.hello()
Hello World!

just my 2 cents, sorry if this couldn't help you.



来源:https://stackoverflow.com/questions/1777752/python-importing-using-cdll-with-a-linux-so-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!