【问题标题】:How to call in C# a DLL function (C++) which uses a pointer as a parameter? [closed]如何在 C# 中调用使用指针作为参数的 DLL 函数 (C++)? [关闭]
【发布时间】:2021-02-11 13:33:47
【问题描述】:

我正在尝试在 C# 中调用一个名为 Function_A(Class1* input_class) 的 DLL 函数(用 C++ 编写)。这是我在 C# 中声明的类。我已经阅读过在 Function_A 声明中某处使用 ref 关键字的信息,但我不确定。任何帮助将不胜感激。谢谢!

[DllImport("The_DLL.dll")]
public static extern int Function_A(Class1* input_class);

public struct Class1
{
        int varA;
        int varB;
}

public struct Class2
{
        class1 class1_A;
        class1 class1_B;
}

static void Main(string[] args)
{
        Class2 a = new Class2();
        Function_A(...);
}

【问题讨论】:

标签: c# c++ interop pinvoke dllimport


【解决方案1】:
[DllImport("The_DLL.dll")]
public static extern int Function_A([In, Out]Class1 input_class);

[DllImport("The_DLL.dll", EntryPoint="Function_A")]
public static extern int Function_A2(ref Class1 input_class);


[StructLayout(LayoutKind.Sequential)]
public struct Class1 //a bad name for a struct but hey...
{
        int varA;
        int varB;
}


static void Main(string[] args)
{
        Class1 x = new Class1();
        Function_A(x); // your struct is marshalled so that changes by the external function are marshalled back
        Function_A2(x); // your struct is marshalled so that changes by the external function are NOT marshalled back
}

【讨论】:

    猜你喜欢
    • 2013-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-27
    相关资源
    最近更新 更多