在C#中使用C ++非托管dll

时间:2010-08-18 19:56:03

标签: c#

我正在尝试访问C ++非托管DLL中的函数,我很难获得任何结果。这就是我的目标:

static unsafe void Main(string[] args)
    {
        IntPtr testIntPtr = aaeonAPIOpen(0);

        var DevID = aaeonWdtGetDevID(testIntPtr);

        Console.WriteLine("DevID: " + DevID.ToString()); //Does not work

        byte pbData1 = 0;
        byte pbData2 = 0;

        Console.WriteLine("Before: {0} {1}", pbData1.ToString(), pbData2.ToString());

        aaeon12VData(testIntPtr, &pbData1, &pbData2); //Notice long delay, but doesn't change pbData1 or pbData2

        Console.WriteLine("After: {0} {1}", pbData1.ToString(), pbData2.ToString());
    }


    [DllImport("aonAPI.dll", EntryPoint = "?aaeonWdtGetDevID@@YAGPAX@Z", ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
    public static extern ushort aaeonWdtGetDevID(IntPtr hInst);
    //C++ Code
    //DLLAPI WORD aaeonWdtGetDevID(HANDLE hInst);

    [DllImport("aonAPI.dll", EntryPoint = "?aaeon12VData@@YAJPAXPAE1@Z", ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
    public static extern unsafe IntPtr aaeon12VData(IntPtr hInst, byte* pbData, byte* pbData2);
    // C++ code
    //DLLAPI HRESULT aaeon12VData(HANDLE hInst, BYTE* pbData, BYTE* pbData2);

    [DllImport("aonAPI.dll", EntryPoint = "?aaeonAPIOpen@@YAPAXK@Z", ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
    public static extern IntPtr aaeonAPIOpen(uint reserved);
    // C++ code
    //DLLAPI HANDLE aaeonAPIOpen(DWORD reserved);   

以下是C ++程序如何将API用于12V:

while(hInst == NULL)
{
    hInst = aaeonAPIOpen(0);
}

unsigned char temp;
unsigned char temp2;

if(aaeon12VData(hInst,&temp,&temp2) == S_OK)
{
    m_message.Format(_T("%d.%d"),temp2,temp);
}

这是dumpbin:

      3    2 00001380 ?aaeon12VData@@YAJPAXPAE1@Z
      5    4 00001020 ?aaeonAPIOpen@@YAPAXK@Z
     10    9 00001040 ?aaeonWdtGetDevID@@YAGPAX@Z

2 个答案:

答案 0 :(得分:1)

您的C#代码似乎引用了入口点的损坏名称。这让我非常怀疑 - 可能是错误的。尝试没有损坏的名称(使用预先破坏的名称)。

答案 1 :(得分:1)

我认为如果您进行以下更改以调用“byref”,您将解决您的问题:

public static extern unsafe IntPtr aaeon12VData(IntPtr hInst, ref byte pbData, byte pbData2); 

aaeon12VData(testIntPtr, ref pbData1, ref pbData2);