在桌面创建dll.c文件,将下面代码复制进去。
#include "dll.h"
int sum(int* a, int n)
{ int i,s=0;
for (i=0;i<n;i++) s+=a[i];
return s;
}
int plus(int a, int b)
{ return a+b; }在桌面创建dll.h文件,将下面代码复制进去。#ifndef DLL_H
#define DLL_H
int sum(int* a, int n);
int plus(int a, int b);
#endif在cmd中运行如下命令。
然后桌面上就会多出.o和.so文件。
打开Canopy创建测试程序,文件名为:test.py,并将下面的代码复制到test.py里去。
# -*- coding: utf-8_ -*-
import wx
import ctypes
import sys
sys.path.append('.')
class MyFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, wx.ID_ANY, 'DLL Example', size=(300, 200))
panel = wx.Panel(self, wx.ID_ANY)
In=wx.StaticText(panel, wx.ID_ANY, u" 输入:")
self.InText = wx.TextCtrl(panel, wx.ID_ANY, "1 2", size=(175, -1))
self.InText.SetInsertionPoint(0)
Out=wx.StaticText(panel, wx.ID_ANY, u" DLL计算结果:")
self.OutText = wx.TextCtrl(panel, wx.ID_ANY, " ", size=(175, -1))
Compute=wx.Button(panel, wx.ID_ANY, u"计算", size=(50, -1))
self.Bind(wx.EVT_BUTTON, self.EvtCompute, Compute)
Exit=wx.Button(panel, wx.ID_ANY, u"退出", size=(50, -1))
self.Bind(wx.EVT_BUTTON, self.EvtExit, Exit)
sizer = wx.FlexGridSizer(cols=2, hgap=10, vgap=10)
sizer.AddMany([In, self.InText,Out, self.OutText,Compute,Exit])
panel.SetSizer(sizer)
self.Centre()
# known Canopy bug: absolute filename required
self.cdll=ctypes.CDLL("/home/wx/Desktop/dll.so")
def EvtCompute(self, event):
a=[int(x) for x in self.InText.GetValue().split()]
if len(a)==2:
result=self.cdll.plus(a[0],a[1])
else:
result=self.cdll.sum(ctypes.ARRAY(ctypes.c_int,len(a))(*a),len(a))
self.OutText.SetValue(str(result))
def EvtExit(self, event): self.Destroy()
if __name__ == '__main__':
# import os
# os.chdir(r"your working directory")
app = wx.App()
frame = MyFrame()
frame.Show()
app.MainLoop()注意修改动态链接库的路径名!
然后就可以运行了。
本文介绍了一个C语言DLL的创建过程及其与Python的交互方式。通过具体代码示例展示了如何在C语言中实现基本数学运算并将其导出为DLL,再利用Python的ctypes模块调用DLL中的函数进行计算。
1039

被折叠的 条评论
为什么被折叠?



