AccessViolationException when accessing unmanaged C++ DLL with C#

风流意气都作罢 提交于 2021-02-10 12:31:20

问题


I am trying to access a Double Dummy Solver dll (http://privat.bahnhof.se/wb758135/bridge/dll.html ) of unmanaged C++ code from a C# project, but I get the following error message:

An unhandled exception of type 'System.AccessViolationException' occurred in Dds.Net.dll

Additional information: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.

The error seems to be around calling the method Par which takes the three arguments

struct ddTableResults *tablep, struct parResults *presp, int vulnerable

Specifically, related to passing in the 2nd parameter which is described to be:

struct parResults char parScore[2][16]; char parContractsString [2][128];

Here is my code: My c# struct:

using System.Runtime.InteropServices;

namespace Dds.Net.Integration
{
    [StructLayout(LayoutKind.Sequential)]
    internal struct ParResults
    {
        [MarshalAs(UnmanagedType.ByValArray, SizeConst =32)]
        public char[,] parScore;
        [MarshalAs(UnmanagedType.ByValArray, SizeConst = 256)]
        public char[,] parContractString;


    }
}

dllimport to call the function :

[DllImport("dds.dll")]
        public static extern int Par(DdTableResults tablep, int vulnerable, ParResults parResults);

Any idea of what I can do to get this working?

Many thanks!


回答1:


as far as I understand, you c++ signature is

int Par(struct ddTableResults *tablep, struct parResults *presp, int vulnerable)

the c# one maybe is

[DllImport("dds.dll")]
public static extern int Par(ref DdTableResults tablep, ref ParResults parResults, int vulnerable);

c++ wants a poitner to DdTableResults and ParResults, without ref c# will pass structure by value.



来源:https://stackoverflow.com/questions/33843311/accessviolationexception-when-accessing-unmanaged-c-dll-with-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!