Python调用C/C++初步

测试库要求做到全部自动化--动态添加新的计算图像指标可以直接不用重写底层java程序……这段时间在学Python,由于Python的ctypes可以试python轻松调用动态链接库,从而调用c/c++程序,于是想到可以在添加指标的时候有管理员再上传相关方法的dll或so文件,由Python进行调用新的指标计算方法进行重新计算。不知效果如何,先测试简单的调用:

1、编写test.c
  1. #include <stdlib.h>  
  2.   
  3. int foo(int a, int b)  
  4. {  
  5.     printf("Your input %i and %i\n", a, b);  
  6.     return a + b;  
  7. }  
 
2、 gcc编译:gcc -o test.so -shared -fPIC test.c
3、 编写test.py
  1. import ctypes  
  2. ll = ctypes.cdll.LoadLibrary 
  3. lib = ll("./test.so")  
  4. lib.foo(13)  
4、运行
 python test.py
成功运行Python调用C/C++初步

不过在调用c++文件的时候会发生错误,具体原因不详,但依然可以调用!!!:
1、编写c++文件test2.cpp
#include<iostream>
using namespace std;
void foo2(int a,int b)
{
    cout<<a<<" "<<b<<endl;
}
 
//以下为必须
extern "c"
{
    void cfoo2(int a,int b)
    {
        foo2(a,b);
    }
}
 
2、编译c++文件:
   g++ -o test2.so -shared -fPIC test2.c
3、 编写test2.py
  1. import ctypes  
  2. ll = ctypes.cdll.LoadLibrary 
  3. lib = ll("./test2.so")  
  4. lib.cfoo2(13)
  5.   
4、运行:
python test2.py
成功!

问题补充:
1、在windows下调用dll,如果过python是64位,那么在写dll时编译要用x64,要不然会出现错误的win32提示。
2、在h文件中:
 extern "C" int __declspec(dllexport)add(int x,int y);
 
cpp:
int __declspec(dllexport)add(int x,int y)
{
    cout<<x<<" "<<y<<endl;
    return x+y;
}
 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值