c#

c#dllimport 怎样使用指针类型参数

小樊
137
2024-07-15 15:54:44
栏目: 编程语言

在C#中使用DllImport来调用C或C++编写的DLL时,若需要传递指针类型参数,可以通过将参数声明为IntPtr类型来实现。以下是一个示例:

假设有一个C++编写的DLL,其中有一个函数定义如下:

extern "C" __declspec(dllexport) void SomeFunction(int* ptr)
{
    *ptr = 10;
}

在C#中调用这个DLL的函数时,可以这样写:

using System;
using System.Runtime.InteropServices;

class Program
{
    [DllImport("YourDllName.dll")]
    public static extern void SomeFunction(IntPtr ptr);

    static void Main()
    {
        int value = 0;
        IntPtr ptr = Marshal.AllocHGlobal(sizeof(int));
        Marshal.WriteInt32(ptr, value);

        SomeFunction(ptr);

        value = Marshal.ReadInt32(ptr);

        Marshal.FreeHGlobal(ptr);

        Console.WriteLine(value);
    }
}

在上述代码中,首先定义了一个[DllImport]标记的静态extern方法SomeFunction,参数为IntPtr类型。在Main方法中,首先分配了一个IntPtr类型的指针ptr,然后将该指针传递给SomeFunction函数。最后使用Marshal.ReadInt32方法从指针指向的内存位置读取值,并输出到控制台上。最后使用Marshal.FreeHGlobal释放分配的内存空间。

需要注意的是,调用DLL函数时要确保参数类型和顺序与DLL函数的声明一致,否则可能会导致程序崩溃或出现异常。

0
看了该问题的人还看了