ubuntu下用python导入c++写的动态链接库
(当前状态:学习图嵌入,遇到metapath2ec的c++代码,想要用python调用,现在知道的方法是将c++生成动态链接库,然后用python直接调用库的函数(要把main当成普通函数来看待,没有什么c++的从主函数执行的))
下面三个关于生成库的链接(就看看)
https://blog.youkuaiyun.com/qq_33850438/article/details/52014399
https://www.cnblogs.com/johnice/archive/2013/01/17/2864319.html
https://blog.youkuaiyun.com/glw0223/article/details/89642244
下面这个就很有用了!有怎么导入的具体步骤解释和代码
https://www.cnblogs.com/spxcds/p/5345345.html
1. 生成库
1.1静态库(没用到,just记录一下)
gcc -c metapath2vec.cpp
gcc -c distance.c
ar -rsv libtest.a metapath2vec.o distance.o
ranlib libtest.a
1.2动态库
g++ metapath2vec.cpp -fPIC -shared -o libmetapath.so #貌似名字前面必须是lib开头的
g++ distance.c -fPIC -shared -o libdistance.so (这个没用到?)
2. 导入
2.1 准备
我用的c++代码有main函数,那个argv是char**类型,传参很多问题!大约查了3个小时资料终于可以正常传参了。下面是有用了链接
https://www.cnblogs.com/spxcds/p/5345345.html 这是一个基础教程
https://tieba.baidu.com/p/5213249142?red_tag=1935817052 这是一个思路,虽然对于我不好用
https://stackoverflow.com/questions/37888565/python-3-5-ctypes-typeerror-bytes-or-integer-address-expected-instead-of-str 这里说明了python版本遇到的问题!
https://www.programcreek.com/python/example/1243/ctypes.c_char_p 这是Python ctypes.c_char_p() Examples(有助于了解)
!!!最后依靠下面的博客解决的
https://blog.youkuaiyun.com/killboss12/article/details/86314883
2.2 以下是python调用so动态库的代码
#coding=utf8
from ctypes import *
cur = cdll.LoadLibrary('./a.so')
argc = 11
cur.main.argtypes=[c_int, POINTER(c_char_p)]#设置格式
string_buffers = [create_string_buffer(64) for i in range(1)]
pointers = (c_char_p*5)(*map(addressof, string_buffers))
#上面一行我是黄的,不知道为什么,反正能跑
pointers[0]='23'.encode('utf-8')#python3.7的c_char_p需要编码-->bytes,str类型不行
pointers[1]='23'.encode('utf-8')
pointers[2]='ddd'.encode('utf-8')
pointers[3]='rfgh'.encode('utf-8')
pointers[4]='tyhnj'.encode('utf-8')
#pointers[4]=c_char_p('tyhnj'.encode('utf-8'))也是可以的
cur.main(31, pointers)