C#中调用dll

1 篇文章 0 订阅
 
原来在编写 Delphi程序时,编写了很多Dll,这些动态库中包含了很多有用的公共函数。由于现在主要编写C#程序,如何在c#中调用这些dll中的函数对于代码的利用变得很重要。
调用 dll中的函数,一般分为静态加载和动态加载。静态加载的方法是:
[ DllImport("MyDelphiDll.dll")]
public static extern int ChangeStrToInt(string beChangedStr);
 
动态加载的方法是使用原来 windows中的api函数来实现,主要的函数包括:LoadLibrary;FreeLibrary;GetProcAddress。这些函数的使用必须在代码中先定义后才可以使用,定义它们的代码被封装到了一个类中,类的代码如下所示:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
 
namespace Seaver.ShareClasses.Windows
{
    class WindowsApiClass
    {
        [DllImport("Kernel32.dll")]
        public static extern int LoadLibrary(string lpFileName);
 
        [DllImport("Kernel32.dll")]
        public static extern bool FreeLibrary(int hModule);
 
        [DllImport("Kernel32.dll")]
        public static extern IntPtr GetProcAddress(int hModule, string lpProcName);
 
        public static Delegate GetAddress(int dllHandle, string functionName, Type t)
        {
            IntPtr functionAddr = GetProcAddress(dllHandle, functionName);
 
            if (functionAddr == null)
                return null;
            else
                return Marshal.GetDelegateForFunctionPointer(functionAddr, t);
        }
 
        private int myDllHandle;
        WindowsApiClass(string dllFilePath)
        {
            myDllHandle = LoadLibrary(dllFilePath);
        }
 
        ~WindowsApiClass()
        {
            myDllHandle = 0;
        }
 
    }
}
GetProcAddress方法返回的类型为指针类型,通过 asp.net中的Marshal类的静态方法GetDelegateForFunctionPointer来将返回的指针转换为委托函数,在类中通过定义GetAddress函数来完成加载和转换的操作。
 
值得注意的是,在编写测试代码时,编写了两个函数,它们的定义是:
Function ChangeIntToStr(piBeChangeInt : Integer) : String; Stdcall;
Function ChangeStrToInt(psBeChangeStr : String) : Integer; Stdcall;
结果在调用 ChangeIntToStr时,出现一场错误,显示内存不可访问,分析后发现在Delphi中String是值类型,而在c#中string是引用类型,所以会出现上述的错误。将Delphi函数定义中的String修改为Pchar,重新执行代码,一切正常。所以在Delphi的dll中定义函数时要注意,对于字符串型参数,一定要使用Pchar,而不要使用String。
原来在 Delphi与C++的Dll编程时也碰到过这种问题,需要遵循相同原则。
 
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值