Linux环境下创建并使用动态链接库

来源:互联网 发布:淘宝智能客服机器人 编辑:程序博客网 时间:2024/06/04 18:15

在桌面创建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 wximport ctypesimport syssys.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()
注意修改动态链接库的路径名!

然后就可以运行了。


原创粉丝点击