从 .NET 创建和调用 C 函数 DLL
解释如何从 .NET 调用 C 函数 DLL
引言
我将给出一个如何创建 C DLL 函数并从 VB.NET 调用它的例子。 这很简单,但有一些任务你必须做。
首先,创建一个 C DLL 项目。 使用 VC++ 6,从 File new project 向导中,选择 Win32 Dynamic-Link Library,单击 OK。 选择一个空的 DLL 项目,因为我们只想创建一个简单的 DLL。 单击下一步。
现在添加一些文件。 从 File new 中,选择 Files 标签,选择 C++ Source File,将其命名为例如 Simple.c。 通过创建 Simple.def 文件重复上一步。
双击 Simple.c 并添加以下代码
#include <WINDOWS.H>
      LPCSTR DisplayStringByVal(LPCSTR pszString)
      {
          return "Hallo apa kabar ";
      }
    void ReturnInParam(int* pnStan, char** pMsg)
    {
        long *buffer;
        char text[] = "Hallo ";
        char name[sizeof(*pMsg)];
         strcpy(name, *pMsg);
        *pnStan = *pnStan + 5;
        buffer = (long *)calloc(sizeof(text)+sizeof(*pMsg), sizeof( char ) );
        *pMsg = (char *)buffer;
        // do not free the buffer, because it will be used by the caller
        // free( buffer );
         strcpy(*pMsg, text);
         strcat(*pMsg, name);
      }
第一个函数只是返回string "Hallo apa kabar" 而不处理任何内容。 第二个函数在 pMsg 参数前面添加 "Hello",并用 5 加上 pnStan 参数。 例如,如果你从 VB.NET 代码调用第二个函数,如下所示
    <DllImport("E:\Temp\simple.dll", CallingConvention:="CallingConvention.Cdecl)"> _
    Private Shared Sub ReturnInParam(ByRef Stan As Integer, _
        ByRef Message As String)
    End Sub
    Private Sub Button1_Click(ByVal sender As System.Object, _
        ByVal e As System.EventArgs) Handles Button1.Click
        Dim Num As Integer = 8
        Dim Message As String = "Harun"
        ReturnInParam(Num, Message)
        MessageBox.Show(Message)
    End Sub
在调用该函数之后,Num 变量的值是 13,并且消息框将提示 Hello Harun。
以下是代码中一些重要事项的说明。 让我们看看 C 中的函数声明
void ReturnInParam(int* pnStan, char** pMsg)
代码...
int* pnStan
...表示你想通过引用传递参数,而不是通过值。 你可以在 VB 代码中看到这一点
Private Shared Sub ReturnInParam(ByRef Stan As Integer, _ ... 
代码...
char** pMsg 
...也表示相同的事情。 我在这里放两个星号 (*) 的原因是 .NET 将 char* 翻译为带有单引号的 string 并通过值传递参数。 因此,如果我想通过引用(或作为指针)传递 string,那么我必须再放一个星号。
其余的 C 代码是关于将 5 添加到 pnStan 并在 pMsg 的开头添加 "Hello"。 你必须懂 C 才能理解该代码。
在编译 C 文件之前,还有一个最后一步需要完成
在 Simple.def 文件中定义库和函数,如下所示
LIBRARY Simple
      DESCRIPTION 'Sample C DLL for use with .NET'
      EXPORTS
        DisplayStringByVal
        ReturnInParam
这告诉 VB 在哪里找到函数入口点。 如果你没有提供此声明,那么你将收到这样的消息
An unhandled exception of type 'System.EntryPointNotFoundException' 
    occurred in Call_C_dll.exe
Additional information: Unable to find an entry point named ReturnInParam 
    in DLL E:\Temp\simple.dll.
好吧,就这些了,很简单,不是吗?




