Python 和C++互调demo(Mac下验证OK)

该示例展示了如何在C++中定义一个回调函数类型,并在Python中通过ctypes库调用C++动态链接库,传递回调函数实现两者之间的通信。在Python中定义了一个回调函数,然后传递给C++的`call_callback`函数执行,成功实现了从Python到C++的数据传递和计算。
摘要由CSDN通过智能技术生成

 library.h

#ifndef PYCTYPESDEMO_LIBRARY_H
#define PYCTYPESDEMO_LIBRARY_H

extern "C" {

typedef int (*callback_example_t)(int*, int);

void hello();
int  call_callback(callback_example_t func, int *pa, int pb);


};

#endif //PYCTYPESDEMO_LIBRARY_H

library.cpp

#include "library.h"

#include <iostream>

void hello() {
    std::cout << "Hello, World!" << std::endl;
}


int call_callback(callback_example_t func, int *pa, int b)
{
    int ret = -1;
    std::cout << "call_callback in C++" << std::endl;
    if (func != nullptr) {
        ret = func(pa, b);
    }
    std::cout << "call_callback in C++ return " << ret << std::endl;

    return ret;
}

CMakefiles.txt

cmake_minimum_required(VERSION 3.17)
project(PyCtypesDemo)

set(CMAKE_CXX_STANDARD 14)
set(PYTHON_ROOT "/Users/***/.pyenv/versions/3.7.0")

include_directories(${PYTHON_ROOT}/include/python3.7m)

link_directories(${PYTHON_ROOT}/lib)

add_library(PyCtypesDemo SHARED library.cpp library.h)

target_link_libraries(PyCtypesDemo libpython3.7m.a)

 demo.py

from ctypes import *

LIB_PATH = '/Users/***/CLionProjects/PyCtypesDemo/cmake-build-debug/libPyCtypesDemo.dylib'
libcpp = cdll.LoadLibrary(LIB_PATH)

libcpp.hello()

CMPFUNC = CFUNCTYPE(c_int, POINTER(c_int), c_int)


def callback_example_python(a, b):
    i = 0
    print('callback_example_python ', b, ' count')
    while i < b:
        print('callback_example_python ', a[i], b)
        i=i+1

    print('callback_example_python return ', b)
    return b


callback_func = CMPFUNC(callback_example_python)

INPUT = c_int * 4
input = INPUT()
input[0] = 11
input[1] = 2
input[2] = 3
input[3] = 4

print('start call callback python->c++')
ret = libcpp.call_callback(callback_func, input, 4)

print('ret=', ret)

运行日志

***@PC001 PyCtypesDemo % python3 api.py
Hello, World!
start call callback python->c++
call_callback in C++
callback_example_python  4  count
callback_example_python  11 4
callback_example_python  2 4
callback_example_python  3 4
callback_example_python  4 4
callback_example_python return  4
call_callback in C++ return 4
ret= 4
***@PC001 PyCtypesDemo % 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

sanzhong104204

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值