python调用c动态库函数_python3调用C动态库函数

  • Post author:
  • Post category:python


制作动态库

#include #include #include #include #include using namespace std;

extern “C” float Dist(float ax,float ay,float az,float bx,float by,float bz){

return(sqrt((ax-bx)*(ax-bx)+(ay-by)*(ay-by)+(az-bz)*(az-bz)));

}

extern “C” int sum(int a,int b){

return a+b;

}

extern “C” void print(int num){

printf(“num is [%d]\n”,num);

}

extern “C” char *getName(char *name){

printf(“name is [%s]\n”,name);

std::string name_str(name);

std::string res = “-$-” + name_str;

printf(“return [%s]\n”,res.data());

return (char *)res.data();

}

编译语句为

g++ -o wanjun.so -shared -fPIC wanjun.cpp

得到动态库 wanjun.so

python3 调用

import platform

from ctypes import *

if platform.system() == ‘Linux’:

libwanjun = cdll.LoadLibrary(‘./wanjun.so’)

libsum = libwanjun.sum

libsum.argtypes = [c_int,c_int]

libsum.restype = c_int

res = libsum(12,13)

print(‘res is ‘,res)

name = “liubei”

getName = libwanjun.getName

getName.argtypes = [c_char_p]

getName.restype = c_char_p

res = getName(name.encode()).decode()

# res = getName(name.encode(“utf-8”)).decode(“utf-8”)

print(“res type is “,type(res))

print(“res name “,res)

首先使用 libwanjun = cdll.LoadLibrary(’./wanjun.so’) 获得动态库,并且命名为 libwanjun。

接下来

libsum = libwanjun.sum

libsum.argtypes = [c_int,c_int]

libsum.restype = c_int

res = libsum(12,13)

print(‘res is ‘,res)

获得库文件中的 c 函数 sum 的 interface ,指定传入的参数类型以及返回的参数类型,即可使用。

note 需要注意的地方

python3 中 str 要转换成 c 中的 char * 需要使用 str.encode() ; (encode 默认使用 utf-8)



版权声明:本文为weixin_35600779原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。