python与c++之前相互调用方法

1、可以使用cython,编写api.pyx:

from libcpp.string cimport string
from libcpp cimport bool

cdef extern from "pyptapi.h" namespace "test":
    void init_log(const char *, const char *)

    cdef int test_pass(const string passwd)

import os
import sys
import time
import threading

def init_priv(passwd):
    return test_pass(passwd)

def _main(fname, exec_in_encrypted_env=False):
    return

然后调用命令:

cython --cplus api.pyx

生成api.cpp,使用api.cpp加入编译生成so库,在python中引用so库,并使用api.pyx中定义的函数即可

如果需要传递数据,比如,传递二进制数组,则可以在api.pyx中这样写:

from libc.string cimport memcpy
from libc.stdlib cimport malloc, free

def proc_file(path):
    
    cdef char* output = NULL
    cdef long len = 0
    proc_file(path, output, len) #c函数,读取文件,为output申请内存,并将数据写入output,同时输出len
    print len
    try:
        return output[:len] # 返回bytes类型的str
    finally:
        free(output)

2、使用pybind,可以通过c++调用python

联系方式:emhhbmdfbGlhbmcxOTkxQDEyNi5jb20=
原文地址:https://www.cnblogs.com/zl1991/p/15035022.html