Python调用C/C++初步

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

一、编写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. }  
 
二、 gcc编译:gcc -o test.so -shared -fPIC test.c
三、 编写test.py
  1. import ctypes  
  2. ll = ctypes.cdll.LoadLibrary 
  3. lib = ll("./test.so")  
  4. lib.foo(13)  
四、运行
 python test.py
成功运行 Python调用C/C++初步

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

问题补充:
一、在windows下调用dll,若是过python是64位,那么在写dll时编译要用x64,要否则会出现错误的win32提示。
二、在h文件中:
Cpp代码    收藏代码
  1. extern "C" int __declspec(dllexport)add(int x,int y);  
 
cpp:
Cpp代码    收藏代码
  1. int __declspec(dllexport)add(int x,int y)  
  2. {  
  3.     cout<<x<<" "<<y<<endl;  
  4.     return x+y;  
  5. }  
 
相关文章
相关标签/搜索