加入收藏 | 设为首页 | 会员中心 | 我要投稿 汽车网 (https://www.0577qiche.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 教程 > 正文

Python 和 C语言的相互调用

发布时间:2023-04-12 14:14:31 所属栏目:教程 来源:
导读:第一种、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, in
第一种、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++可执行程序
#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;
}

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

(编辑:汽车网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章