C#代码需要调用C开发的动态库时,可以使用DLLImport的方式。
using System;
using System.Runtime.InteropServices;
class Example
{
// Use DllImport to import the Win32 MessageBox function.
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
public static extern int MessageBox(IntPtr hWnd, String text, String caption, uint type);
static void Main()
{
// Call the MessageBox function using platform invoke.
MessageBox(new IntPtr(0), "Hello World!", "Hello Dialog", 0);
}
}
通过DllImport来指定调用的dll及其路径,调用规范和entery point,通常这个新定义的函数和DLL中的函数同名,如果遇到传入数组形式如double *,C#使用double[]代替,如果传入指针类型用于返回参数,如point to int,则在C#中使用ref int形式。
有时代码会报出"Entry Point not found"错误,这可能是DLL生成时没有extern C造成。

本文介绍了如何在C#中使用DLLImport特性调用C语言开发的动态库,详细阐述了DllImport的用法,包括指定DLL路径、函数调用规范和入口点。示例代码演示了调用user32.dll的MessageBox函数,并解释了当遇到EntryPointNotFoundException错误时可能的原因。同时,文章提及了C#中处理数组和指针类型的转换规则。
1641

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



