test.h
#pragma once
#include <stdio.h>
extern "C" int Add(int a, int b);
extern "C" int Max(int a,int b);
test.cpp
#include "test.h"
extern "C" int Add(int a, int b)
{
return a + b;
}
extern "C" int Max(int a, int b)
{
if (a > b)
return a;
return b;
}
注意:#include "stdafx.h"不要写进去否则编译so库出错,第二需要些extern "C",不写可以编译成so库但是调用会提示undefinedsymbol错误
编译成so库,注意先切换到test.cpp所在目录,可以不用加lib
gcc test.cpp -fPIC -shared -o libtest.so
写成gcc test.cpp -fPIC -shared -o test.so也可以会生成test.so库
python调用
from ctypes import cdll
test = cdll.LoadLibrary(/home/username/Downloads/libtest.so)
result = test.Add(4,5)
print(result)