簡體   English   中英

將字符串從本機C ++ DLL傳遞到C#App

[英]Passing String from Native C++ DLL to C# App

我已經用C ++編寫了一個DLL。 函數之一寫入字符數組。

C ++函數

EXPORT int xmain(int argc, char argv[], char argv2[])
{
    char  pTypeName[4096];
    ...
    //Other pTypeName ends up populated with "Portable Network Graphics"
    //This code verifies that pTypeName is populated with what I think it is:
    char szBuff[64];
    sprintf(szBuff, pTypeName, 0);
    MessageBoxA(NULL, szBuff, szBuff, MB_OK);
    //The caption and title are "Portable Network Graphics"

    ...
    //Here, I attempt to copy the value in pTypeName to parameter 3.
    sprintf(argv2, szBuff, 0);

    return ret;
}

C#導入

    //I believe I have to use CharSet.Ansi because by the C++ code uses char[],
    [DllImport("FirstDll.dll", CharSet=CharSet.Ansi)]
    public static extern int xmain(int argc, string argv, ref string zzz);

C#功能

private void button2_Click(object sender, EventArgs e)
{
    string zzz = ""; 
    int xxx = xmain(2, @"C:\hhh.bmp", ref zzz);
    MessageBox.Show(zzz);

    //The message box displays
    //MessageBox.Show displays "IstuÈst¼ÓstÄstlÄstwÄstiÑstõÖstwÍst\
    // aÖst[ÖstÃÏst¯ÄstÐstòÄstŽÐstÅstpÅstOleMainThreadWndClass"

}

我試圖通過引用從C#傳遞參數,並讓C ++ DLL填充該參數。 即使我已驗證DLL中的值正確,亂碼也會傳遞給C#應用程序。

如何將正確的字符串值寫入C#字符串?

使用StringBuilder傳遞本機代碼可以填充的字符數組(請參見“ 固定長度的字符串緩沖區” )。

聲明功能:

[DllImport("FirstDll.dll", CharSet=CharSet.Ansi)]
public static extern int xmain(int argc, string argv, StringBuilder argv2);

用它:

// allocate a StringBuilder with enough space; if it is too small,
// the native code will corrupt memory
StringBuilder sb = new StringBuilder(4096);
xmain(2, @"C:\hhh.bmp", sb);
string argv2 = sb.ToString();

將其他一些信息提供給DLLImport調用。 看下面我自己的例子:

[DllImport("tcpipNexIbnk.dll", EntryPoint = "SendData", CallingConvention = CallingConvention.Cdecl)]
    public static extern int Send([MarshalAs(UnmanagedType.LPWStr)]string message);

注意兩件事,CallingConvention參數:CallingConvention = CallingConvention.Cdecl)

照原樣使用。

然后緊隨C#字符串類型之后,您可以使用MarshalAS指令使用不同的非托管類型,該指令會將C#字符串參數轉換為您在c ++程序中具有的本機字符串類型:

public static extern int Send([MarshalAs(UnmanagedType.LPWStr)]string message);

希望能幫助到你。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM