对C++不熟,在python中调用c++程序
先撰写.cpp程序
#include <iostream>
extern "C"
{
void bbar(){
std::cout<<"Hello"<<std::endl;
}
}
编译.cpp为.so文件(每次写完cpp都得编译一次)
g++ -std=c++11 -shared -fPIC -o t.so t.cpp -I/usr/include/python3.6
.py 程序
#!/usr/bin/env python
# coding=utf-8
from ctypes import cdll
lib = cdll.LoadLibrary('t.so')
if __name__=="__main__":
lib.bbar()
cpp
#include <iostream>
extern "C"
{
int bbar(int a, int b){
return a+b;
}
}
py
#!/usr/bin/env python
# coding=utf-8
from ctypes import cdll
lib = cdll.LoadLibrary('t.so')
if __name__=="__main__":
#f = F()
a = lib.bbar(1,2)
print(a)
感觉ctypes调用class 不是很方便啊,查到一些demo,class实例化还是在c++里
.cpp文件
#include <iostream>
#include <ostream>
#include <type_traits>
#include <typeinfo>
using namespace std;
class Test
{
public:
int add(int a, int b);
int subtraction(int a, int b);
void print(const char *s);
};
int Test::add(int a, int b)
{
return a+b;
}
int Test::subtraction(int a, int b){
return a-b;
}
void Test::print(const char *s){
cout << s <<endl;
};
extern "C"{
Test T;
int _add(int a, int b){
int c;
c = T.add(a,b);
return c;
}
int _sub(int a, int b){
int c;
c = T.subtraction(a,b);
return c;
}
void _print(const char *s){
T.print("c++");
//if (typeid(s).name() == "string")
T.print(s);
}
}
编译成动态库后
.py文件
#!/usr/bin/env python
# coding=utf-8
from ctypes import cdll,c_char_p
lib = cdll.LoadLibrary('t.so')
if __name__=="__main__":
# f = lib.T()
a = lib._add(1,2)
b = lib._sub(1,2)
print(a)
print(b)
lib._print(c_char_p(bytes("python", 'utf-8')))
要通过 c_char_p 把输入转成char 指针,否则只会print 第一个字符"p".