前言

这个我查询了很多资料,所以到此为止,相当于做一个总结

c++代码如何生成dll

#include<iostream>

using namespace std;

extern "C" __declspec(dllexport) int add(int a,int b);

int add(int a, int b){
return a + b;
}


int main(){
cout << add(1,2) << endl;
return 0;
}

这里的 ​​extern​​​那一行相当于为 python提供了调用接口,如果写好函数后,一定要按照那一行的格式进行声明,否者无法进行调用。
编译命令:

g++ -shared test.cpp -o test.dll

这里的源码文件为 ​​test.cpp​​​,会生成 ​​test.dll​​文件

python调用方法

from ctypes import *
import ctypes
dll = ctypes.cdll.LoadLibrary('test.dll')
print(s)

输出:3
调用成功

字符串传递方法

我当时想用c++实现一个加密算法,然后需要传递字符串,所以这部分才是有意思的,并且网上几乎查不到。

python 与c++互相传递字符串

由于c++存储字符串只能通过字符数组(也可以使用string类,但是由于需要与python进行交互,就必须用c支持的),所以这样写

#include<iostream>
using namespace std;
extern "C" __declspec(dllexport) int add(int a,int b);
extern "C" __declspec(dllexport) char* Rstring(char *s,int count);
int add(int a, int b){
return a + b;
}

char* Rstring(char *s,int count){
for (int i = 0; i < count; ++i)
{
cout << s[i];
}
return s;
}

int main(){
cout << add(1,2) << endl;
return 0;
}

python方面:

from ctypes import *
import ctypes

dll = ctypes.cdll.LoadLibrary('test.dll')
s = dll.Rstring(b'hello world',11)
print(s)
print(c_char_p(s).value)

这里,有一个有意思的函数 ​​c_char_p​​,这个函数可以通过指针来找到指针所指向的地址中的值,也就是专门为指针准备的函数,由于c++返回的是一个指针,所以我们用到了这个函数,另外传递和传出的字符串都说 b‘’开头的,也就是字节型数据。


作者:Hello_wshuo​