需求一:制作DLL 返回字符串 以供python使用
main.cpp文件
#include "main.h"
#include <comdef.h>
using namespace std;
void func_xws(const WCHAR *strUnicode,WCHAR* sometext,int len);
void DLL_EXPORT SomeFunction(WCHAR* sometext,int len)
{
WCHAR *strUnicode = L"{'name':'xingwenshuang','gender':'female'}";
func_xws(strUnicode,sometext,len);
}
void func_xws(const WCHAR *strUnicode,WCHAR* sometext,int len)
{
for(int i = 0;i<len;i++)
{
*sometext = *strUnicode;
sometext++;
strUnicode++;
}
}
main.h文件
#ifndef __MAIN_H__
#define __MAIN_H__
#include <windows.h>
/* To use this exported function of dll, include this header
* in your project.
*/
#ifdef BUILD_DLL
#define DLL_EXPORT __declspec(dllexport)
#else
#define DLL_EXPORT __declspec(dllimport)
#endif
#ifdef __cplusplus
extern "C"
{
#endif
void DLL_EXPORT SomeFunction(WCHAR* sometext,int len);
#ifdef __cplusplus
}
#endif
#endif // __MAIN_H__
最终python调用程序
test.py文件
import ctypes
from ctypes import *
dll = ctypes.windll.LoadLibrary( r'....Dll.dll' )
buffer = ctypes.create_unicode_buffer("hello", size=256)
bufferLen = ctypes.c_int(256)
content = dll.SomeFunction(ctypes.pointer(buffer),bufferLen)
print("return: ", content, buffer.value)
输出:
需求二:linux,制作动态库.so文件,包含类调用,以及python调用
参数:char* 、int*
test.cpp
#include "test.h"
#include <iostream>
using namespace std;
//子类定义
class myCap : public WntimeCap {
public:
myCap();
~myCap();
void Init(char *gst);
};
myCap::myCap()
{
}
myCap::~myCap()
{
}
void myCap::Init(char* uri)
{
std::cout<<"-----------init now----\n"<<std::endl;
}
extern "C"{
// 创建对象
myCap* MyCreate(){
printf("------------create\n");
return new myCap;
}
//初始化
void init(myCap* t,char * gst,int* ret){
printf("-------------init\n");
t->Init(gst);
*ret = 0;
printf("-------------init-end\n");
}
test.h
#ifndef TEST_H
#define TEST_H
class WntimeCap {
public:
WntimeCap();
virtual ~WntimeCap();
void Init(char* uri);
};
// 父类定义 WntimeCap
WntimeCap::WntimeCap()
{
}
WntimeCap::~WntimeCap()
{
}
#endif
cmakelist.txt
cmake_minimum_required(VERSION 3.13)
project(test)
set(CMAKE_CXX_STANDARD 14)
add_library(test SHARED test.cpp test.h)
mkdir build
cd build
cmake ..
make
test.py
import ctypes
so = ctypes.CDLL('libtest.so') # 动态库加载
obj = so.MyCreate() # 创建对象
arg = ctypes.c_char_p(b"https://blog.csdn.net/magic_shuang")
ret = ctypes.c_int()
ret_p = ctypes.pointer(ret)
# 对象初始化
so.init(obj,arg,ret_p)
print(ret.value)