编译命令:g++ test.c fPIC -shared -o libtest.so
call.py:
1 import ctypes
2 from ctypes import *
3 so = ctypes.CDLL("./libtest.so")
4 s = create_string_buffer('/000'*32)
5 so.display(s)
6 print repr(s.value)
7 so.display_int(1)
test.c:
1 #include <iostream>
2 #include <string>
3 using namespace std;
4
5 class TestLib{
6 public:
7 void display(char* strTest);
8 void display(int a);
9 };
10
11 void TestLib::display(char* strTest)
12 {
13 //strTest = "helloo";
14 strcpy(strTest,"hellooworld!!");
15 cout<<"fist display"<<endl;
16 }
17
18 void TestLib::display(int a)
19 {
20 cout<<"second dispay"<<endl;
21 }
22
23 extern "C"{
24 TestLib obj;
25 void display(char* str)
26 {
27 obj.display(str);
28 }
29
30 void display_int(){
31 obj.display(2);
32 }
33 }
调用C++时,传入的是字符串。
参考资料:
ctypes使用方法:http://blog.csdn.net/jhonguy/article/details/7698350
python和python相互调用:http://www.linuxidc.com/Linux/2011-10/44837.htm