python调用C/C++动态链接库和jython

总结(非原创)

Python调用C库比较简单,不经过任何封装打包成so,再使用python的ctypes调用即可。

1. C语言文件: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;
}

2. gcc编译成动态库libpycall.so: gcc -o libpycall.so -shared -fPIC pycall.c

3. python调用动态库的文件:pycall.py

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

4. 运行结果

you input 1 and 3
4
***finish****

 调用C++动态链接库,需要借助extern "C"来实现

1.C++文件(.cpp)

#include <iostream>
using namespace std;

class TestLib
{
     public:
         int display();
         void display(int a);
};

int TestLib::display() {
    cout<<"First display"<<endl;
    int num = 233333;
    return num;
}


void TestLib::display(int a) {
     cout<<"Second display:"<<a<<endl;
}

extern "C" {
     TestLib obj;
     int display() {
         return obj.display();
     }
     void display_int(int b) {
         obj.display(b); 
     }
}

2.g++编译成动态库:g++ -o libpycallclass.so -shared -fPIC pycallclass.cpp

3.python调用动态库文件:

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

4.结果如下:

First display
233333
Second display:0

 通过Jython扩展python(java)

1.java文件(JythonTest.java)

public class JythonTest{
    private String user;
    public JythonTest(String UserName){
        user = UserName;
    }
    public void greeting(){
        System.out.println(user+"Hello World!");
    }
}

2.通过java编译器进行编译:javac JythonTest.java

3.python调用文件

#usr/bin/python

import JythonTest

test = JythonTest("Mr. L!")
test.greeting()

4.结果

Mr. L!Hello World!
posted @ 2015-11-19 09:43  dayday+up  阅读(561)  评论(0编辑  收藏  举报