0
点赞
收藏
分享

微信扫一扫

Python 和 C语言的相互调用

 

第一种、Python调用C动态链接库(利用ctypes)

下面示例在linux或unix下可行。

pycall.c

/***gcc -o libpycall.so -shared -fPIC pycall.c*/
#include <stdio.h> 
#include <stdlib.h> 
int foo(int a, int b) 
{ 
printf("you input %d and %d\n", a, b); 
return a+b; 
}

pycall.py

import ctypes 
ll = ctypes.cdll.LoadLibrary  
lib = ll("./libpycall.so")  
lib.foo(1, 3) 
print '***finish***'

运行方法:

gcc -o libpycall.so -shared -fPIC pycall.c
python pycall.py

 

第2种、Python调用C++(类)动态链接库(利用ctypes)

pycallclass.cpp

#include <iostream> 
using namespace std; 
 
class TestLib 
{ 
public: 
void display(); 
void display(int a); 
}; 
void TestLib::display() { 
cout<<"First display"<<endl; 
} 
 
void TestLib::display(int a) { 
cout<<"Second display:"<<a<<endl; 
} 
extern "C" { 
TestLib obj; 
void display() { 
obj.display();  
} 
void display_int() { 
obj.display(2);  
} 
}

pycallclass.py

import ctypes 
so = ctypes.cdll.LoadLibrary  
lib = so("./libpycallclass.so")  
print 'display()'
lib.display() 
print 'display(100)'
lib.display_int(100)

运行方法:

g++ -o libpycallclass.so -shared -fPIC pycallclass.cpp
python pycallclass.py

 

第3种、Python调用C和C++可执行程序

main.cpp

#include <iostream> 
using namespace std; 
int test() 
{ 
int a = 10, b = 5; 
return a+b; 
} 
int main() 
{ 
cout<<"---begin---"<<endl; 
int num = test(); 
cout<<"num="<<num<<endl; 
cout<<"---end---"<<endl; 
}

main.py

import commands 
import os 
main = "./testmain"
if os.path.exists(main): 
rc, out = commands.getstatusoutput(main) 
print 'rc = %d, \nout = %s' % (rc, out) 
 
print '*'*10
f = os.popen(main)  
data = f.readlines()  
f.close()  
print data 
 
print '*'*10
os.system(main)

 

运行方法(只有这种不是生成.so然后让python文件来调用):

g++ -o testmain main.cpp
python main.py

 

疑问:

Windows 如何实现?

 

 

 

REF

https://www.jb51.net/article/165362.htm

 



举报

相关推荐

0 条评论