python 调用c写的dll/so


1. 先上python代码:

#!/usr/bin/env python
#coding: utf-8

import ctypes
from ctypes import * 

CHARARRAY32 = c_char * 32;
CHARARRAY128 = c_char * 128;

# 数据结构
class MyData(Structure):  
    _fields_ = [  
		("desc", CHARARRAY128),  
		("mac", CHARARRAY32),
		("name", CHARARRAY128),
		("dhcp", c_int),
		("temperature", c_float)
		]  

# 加载dll
dll=ctypes.cdll.LoadLibrary("libpythonif.so")
		
# 调用GetMyData,假设dll有“GetMyData”函数
def GetMyData():
	GetMyData = dll.GetMyData
	GetMyData.restype = c_int
	GetMyData.argtypes = [POINTER(MyData)]
	zdsData = MyData()
	GetMyData(byref(zdsData))
	return zdsData

2. c 代码:

#ifdef _WIN32

#define DLL_EXPORT __declspec(dllexport)
#define CALL_METHOD __cdecl

#else

#include 
#include 
#include 
#include 
#include 

#define DLL_EXPORT __attribute ((visibility("default")))
#define CALL_METHOD 

#endif

struct MyData  
{
	char desc[128];
	char mac[32];
	char name[128];
	int dhcp;
	float temperature;
};  

DLL_EXPORT int CALL_METHOD GetMyData(struct MyData* TheData)
{
	strncpy(TheData->desc, "I am the data", 128);
	return 0;
}

3. python调用c的动态库非常方便

dll=ctypes.cdll.LoadLibrary("libpythonif.so")

稍稍麻烦的地方在于传递参数,用一个结构体来传递输入输出参数,也变得很容易




你可能感兴趣的:(python 调用c写的dll/so)