python调用C++的类
时间: 2023-10-12 10:14:31 浏览: 103
可以使用Python的ctypes模块来调用C的类。
以下是一个示例:
C代码:
```c
#include <stdio.h>
class MyClass {
public:
int value;
MyClass(int value) {
this->value = value;
}
void print() {
printf("MyClass value: %d\n", value);
}
};
extern "C" {
MyClass* MyClass_new(int value) {
return new MyClass(value);
}
void MyClass_print(MyClass* self) {
self->print();
}
void MyClass_delete(MyClass* self) {
delete self;
}
}
```
Python代码:
```python
import ctypes
class MyClass(object):
def __init__(self, value):
self.value = value
lib.MyClass_new.argtypes = [ctypes.c_int]
lib.MyClass_new.restype = ctypes.c_void_p
self.obj = lib.MyClass_new(value)
def print(self):
lib.MyClass_print.argtypes = [ctypes.c_void_p]
lib.MyClass_print.restype = None
lib.MyClass_print(self.obj)
def __del__(self):
lib.MyClass_delete.argtypes = [ctypes.c_void_p]
lib.MyClass_delete.restype = None
lib.MyClass_delete(self.obj)
lib = ctypes.cdll.LoadLibrary('./myclass.so')
myclass = MyClass(10)
myclass.print()
```
注意:C++类的构造函数、析构函数和成员函数都需要使用extern "C"声明为C函数,以便在Python中调用。同时,在Python中调用C++类的成员函数时,需要先设置argtypes和restype。
阅读全文