python如何调用C++外部库中的类?

Python021

python如何调用C++外部库中的类?,第1张

你好流程比较复杂,需要通过一个c的接口来做。下面是一个简单的例子,你也可以到booth去看看他们是怎么用的。

//YourFile.cpp (compiled into a .dll or .so file)

#include

//For std::nothrow

//Either include a header defining your class, or define it here.

extern "C" //Tells the compile to use C-linkage for the next scope.

{

//Note: The interface this linkage region needs to use C only.

void * CreateInstanceOfClass( void )

{

// Note: Inside the function body, I can use C++.

return new(std::nothrow) MyClass

}

//Thanks Chris.

void DeleteInstanceOfClass (void *ptr)

{

delete(std::nothrow) ptr

}

int CallMemberTest(void *ptr)

{

// Note: A downside here is the lack of type safety.

// You could always internally(in the C++ library) save a reference to all

// pointers created of type MyClass and verify it is an element in that

//structure.

//

// Per comments with Andre, we should avoid throwing exceptions.

try

{

MyClass * ref = reinterpret_cast

(ptr)

return ref->Test()

}

catch(...)

{

return -1//assuming -1 is an error condition.

}

}

} //End C linkage scope.

第二步:

gcc -shared -o test.so test.cpp

#creates test.so in your current working directory.

第三步:

>>>from ctypes import cdll

>>>stdc=cdll.LoadLibrary("libc.so.6") # or similar to load c library

>>>stdcpp=cdll.LoadLibrary("libstdc++.so.6") # or similar to load c++ library

>>>myLib=cdll.LoadLibrary("/path/to/test.so")

>>>spam = myLib.CreateInstanceOfClass()

>>>spam

[outputs the pointer address of the element]

>>>value=CallMemberTest(spam)

[does whatever Test does to the spam reference of the object]

今天遇到同样的问题,就来答一波吧

1,如果是在类中,那么就很简单了,类中的一个函数调用另一个函数,只要在那个被调用的函数前加self即可(图如下,详细可以参考笔者博客),

2,如果不是在类中,(这是笔者遇到的问题),有一个简单的方法,如下sin_f函数调用sin函数(注:a=sin()不能写到sin_f()函数下,会说a没声明就调用):

3,如果是已经存在的包,那么调用包更简单了,(同样可以参考笔者上面给的那个博客第四部分)

4,最后,更多关于python问题可以参考笔者的python教程笔记