1. 程式人生 > >python 呼叫C++動態庫所遇到的undefined symbol ***

python 呼叫C++動態庫所遇到的undefined symbol ***

因為演算法效率問題所以要在python中呼叫C,
先寫一個C函式:

test.cpp 

# include<stdio.h>
# include <stdlib.h>     //atoi
# include <string.h>    //strlen
# include <unistd.h>   //gethostname()
# include <stdint.h>   //uint64_t

int add(int a,int b){
    printf("this is from C dll");
    return a+b;
}

編譯 :

gcc -c -fPIC test.cpp

gcc -shared test.o -o test.so

然後在python中呼叫sum函式:
mylib.py


from ctypes import *
libc=CDLL("test.so")
libc.sum(2,2)

執行:

python mylib.py

出錯:******can not find symbol sum

發現是因為c++編譯後的檔案會把函式名改名(為了實現過載功能)

用extern “C”聲明後,就會使用c的方式進行編譯,編譯後的檔案中仍然是定義的函式名

所以只要講c庫中的程式碼改為:

# include<stdio.h>
# include <stdlib.h>     //atoi
# include <string.h>    //strlen
# include <unistd.h>   //gethostname()
# include <stdint.h>   //uint64_t
extern "C"{
int sum(int,int);

}

int sum(int a,int b){
        printf("this is from C dll");
        return a+b;
}