繁体   English   中英

DllImport C#崩溃

[英]Crash With DllImport C#

我正在使用用MFC C ++编写的第三方API。 我的应用程序是C#中的WinForms应用程序。 API的公司有一个C#演示应用程序,我逐字使用了它们的代码。 相关代码如下:

API的C ++函数:

int PASCAL CppFunction(BYTE *pbAdapterID, BYTE *pbTargetID, char *pcVendor, char *pcProduct, char *pcRelease, int iMessageBox)
{
    // The function definition is all I can see in the API's documentation
}

DllImport声明:

[DllImport("api.dll")]
extern public static int CppFunction(ref byte pbAdapter, ref byte pbTargetID, string pcVendor, string pcProduct, string pcRelease, int iMessageBox);

我的C#逻辑:

public void CallCppFunction()
{
    try
    {
        int result = 0;
        string strVendorBuffer = string.Empty;
        string strProductBuffer = string.Empty;
        string strReleaseBuffer = string.Empty;
        string strSerial = string.Empty;
        byte bAdapt = 0;
        byte bTarg = 0;

        result = CppFunction(ref bAdapt, ref bTarg, strVendorBuffer, strProductBuffer, strReleaseBuffer, 0);
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

这是他们C#示例中存在的代码。 运行时,即使在try / catch中,它也会因“ FatalExecutionEngineError”而崩溃。

在此处输入图片说明

我不太了解PInvoke,但是这些变量不是必须编组为非托管类型吗? 任何帮助,将不胜感激。

我在这里大胆猜测,但是我敢肯定,这将是正确的答案

让我们看一下函数定义:

int PASCAL CppFunction(
    BYTE *pbAdapterID, 
    BYTE *pbTargetID, 
    char *pcVendor, 
    char *pcProduct, 
    char *pcRelease, 
    int iMessageBox);

以及相应的DllImport声明:

[DllImport("api.dll")]
extern public static int CppFunction(
    ref byte pbAdapter, 
    ref byte pbTargetID, 
    string pcVendor, 
    string pcProduct, 
    string pcRelease,
    int iMessageBox);

那里有很多参数,其中一些引起了我的注意:

    char *pcVendor, 
    char *pcProduct, 
    char *pcRelease,

它们没有通过引用传递,是否正在由库修改?

注意:这就是为什么我要求您提供有关该功能的详细信息。

在这种情况下,由于数据类型字符串是不可变的,因此无法封送字符串,必须使用StringBuilder类,只需确保StringBuilder具有足够的Capacity即可

int result = 0;
StringBuilder strVendorBuffer = new StringBuilder(1024); // up to 1024 chars
StringBuilder strProductBuffer = new StringBuilder(1024); // up to 1024 chars
StringBuilder strReleaseBuffer = new StringBuilder(1024); // up to 1024 chars
StringBuilder strSerial = string.Empty;
byte bAdapt = 0;
byte bTarg = 0;

result = CppFunction(ref bAdapt, ref bTarg, strVendorBuffer, strProductBuffer, strReleaseBuffer, 0);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM