python调用C++动态库
生成C++动态库
生成C++ 动态库需要注意以下几点:
1.编译成64位的dll库
如果64位的python调用32位的dll会报下面的错误:
OSError: [WinError 193] %1 不是有效的 Win32 应用程序。
这种错误的原因基本上都是64为的python调用了32位的动态库。
解决的方法是生成64位的动态库。安装了visual studio可以使用:
x64的命令行窗口进行编译。编译命令是:
cl /LD hello.cpp
2. C++ 模板
头文件的模板如下:
//dll.h
#ifndef DLL_EXPORT
#define DECLDIR __declspec(dllimport)
#else
#define DECLDIR __declspec(dllexport)
#endif
c++源文件的模板如下:
//hello.cpp
#include "stdio.h"
#include <iostream>
#include <string.h>
#ifdef __cplusplus
extern "C"
{
#endif
#define DLL_EXPORT
#include "dll.h"
using namespace std;
#pragma execution_character_set("utf-8")
DECLDIR void hello(void){
printf("hello world");
}
DECLDIR int add_int(int a,int b){
return a+b;
}
DECLDIR float add_float(float a,float b){
return a+b;
}
DECLDIR double add_double(double a,double b){
return a+b;
}
DECLDIR char pass_char(char c){
printf("%c\n",char(c));
return c;
}
DECLDIR wchar_t pass_wchar(wchar_t wc){
wcout.imbue(locale("chs"));
wcout<< wc;
return wc;
}
DECLDIR char* pass_str(char *s){
printf("%s\n",s);
return strcat(s,"return");
}
DECLDIR wchar_t* pass_wstr(wchar_t*s,wchar_t wc){
wcout<< s;
wchar_t *p = wcschr(s,wc);
return p;
}
DECLDIR int* get_memory(int n)
{
int *p = new int[n];
for(int i = 0; i < n; i++)
{
p[i] = i;
}
return p;
}
DECLDIR void free_memory(int *p)
{