C#访问本机C ++ DLL

时间:2019-03-21 08:38:35

标签: c# c++ interop

我正在尝试创建访问本机C ++ DLL的程序。下面是示例代码。

C ++代码

GetRmaPin (const char *rma_password, const char *serial, unsigned char *rma_pin);

C#代码

class Program
{
    static void Main ( string [ ] args )
    {
        string[] password = { "74f3d3a287cee548c1842c07090d6a274dd0ddbd04bfd1e4694861a369bc7304" };
        string[] serial = { "184393900006" };
        //StringBuilder rma_pin = new StringBuilder(2048);
        byte[] rma_pin = new byte[2048];

        int rc = GetRmaPin(password, serial, ref rma_pin);
        Console.WriteLine ( "Result: " + rc.ToString ( ) );
        Console.WriteLine ( "Payload: " + rma_pin.ToString ( ) );
        Console.Read ( );
    }

    [DllImport ( "Security.dll" , EntryPoint = "GetRmaPin" , CallingConvention = CallingConvention.Cdecl)]
    public static extern int GetRmaPin (
        [In][MarshalAs ( UnmanagedType.LPArray , ArraySubType = UnmanagedType.LPStr )] string [ ] password ,
        [In][MarshalAs ( UnmanagedType.LPArray , ArraySubType = UnmanagedType.LPStr )] string [ ] serial ,
        ref byte[] rmap_in );
}

错误消息: 托管调试助手“ FatalExecutionEngineError” Message =托管调试助手'FatalExecutionEngineError':'运行时遇到致命错误。错误的地址位于线程0x97a4上的0x732dc93d。错误代码为0xc0000005。此错误可能是CLR或用户代码中不安全或不可验证部分的错误。该错误的常见来源包括COM-interop或PInvoke的用户封送处理错误,这些错误可能会破坏堆栈。'

1 个答案:

答案 0 :(得分:0)

经过一些实验,我找到了一种从第3个参数获取值的方法。这是更新的代码。感谢@HansPassant提供的技巧来删除“ ref”。希望这对以后的人有所帮助。

class Program
{
    static void Main ( string [ ] args )
    {
        string[] password = { "74f3d3a287cee548c1842c07090d6a274dd0ddbd04bfd1e4694861a369bc7304" };
        string[] serial = { "184393900006" };
        byte[] rma_pin = new byte[32];

        int rc = GetRmaPin(password, serial, rma_pin);

        Console.WriteLine ( "Result: " + rc.ToString ( ) );
        Console.WriteLine ( "Payload: " + BitConverter.ToString ( rma_pin ).Replace ( "-" , "" ) );
        Console.Read ( );
    }

    [DllImport ( "SecurityProduction.dll" , EntryPoint = "GetRmaPin" , CallingConvention = CallingConvention.Cdecl)]
    public static extern int GetRmaPin (
        [In][MarshalAs ( UnmanagedType.LPArray , ArraySubType = UnmanagedType.LPStr )] string [ ] password ,
        [In][MarshalAs ( UnmanagedType.LPArray , ArraySubType = UnmanagedType.LPStr )] string [ ] serial ,
        byte[] rmap_in );
}