【水到渠成C++】 c++自定义动态链接库,以供python调用,返回值

需求一:制作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)
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值