You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过P/Invoke将C++(非C++/CLI)TCP接收数据传递给C#

已实现C++与C#通过P/Invoke传递字符串及字符串数组

我已经完成了非C++/CLI的C++与C#之间通过P/Invoke传递字符串及字符串数组的功能,相关代码如下:

C++代码

LibMain.h

#pragma once
#include <string.h>
#include <oleauto.h>

extern "C"
{   
__declspec(dllexport) BSTR __stdcall cpp_test(char* str);

__declspec(dllexport) SAFEARRAY* cpp_test2(char** str_arr, int i);

}

LibMain.cpp

BSTR __stdcall cpp_test(char* str)
{
    wchar_t* pStr;

    int strSize = MultiByteToWideChar(CP_ACP, 0, str, -1, NULL, NULL);

    pStr = new WCHAR[strSize];

    MultiByteToWideChar(CP_ACP, 0, str, strlen(str) + 1, pStr, strSize);

    return SysAllocString(pStr);

}

SAFEARRAY* cpp_test2(char** str_arr, int len)
{

    SAFEARRAY* psa = SafeArrayCreateVector(VT_BSTR, 0, len);
    BSTR HUGEP* arr = NULL;
    SafeArrayAccessData(psa, reinterpret_cast<void HUGEP**>(&arr));

    for (int i = 0; i < len; i++) {
        char* str = str_arr[i];
        wchar_t* pStr;

        int strSize = MultiByteToWideChar(CP_ACP, 0, str, -1, NULL, NULL);

        pStr = new WCHAR[strSize];

        MultiByteToWideChar(CP_ACP, 0, str, strlen(str) + 1, pStr, strSize);

        arr[i] = SysAllocString(pStr);
    }
    SafeArrayUnaccessData(psa);

    return psa;

}

C#代码

[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern bool SetDllDirectory(string lpPathName);

[DllImport(@"CPPSampleLibDll.dll", CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.BStr)]
static extern string cpp_test(string str);

[DllImport(@"CPPSampleLibDll.dll", CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.SafeArray)]
static extern string[] cpp_test2(string[] str_arr, int iSize);

string rootPath = Path.GetFullPath(@".");
SetDllDirectory(rootPath);

string[] test = new string[2];
test[0] = "test0";
test[1] = "test1";

string[] test2 = cpp_test2(test, test.Length);
cpp_test("test2");

foreach (string s in test2)
{
        MessageBox.Show(s);
}

MessageBox.Show(cpp_test("test2"));

目前上述代码可正常实现字符串及字符串数组的传递,运行时能弹出对应消息框。现在希望进一步实现:将非C++/CLI的C++程序通过TCP通信接收的数据传递给C#。

内容的提问来源于stack exchange,提问作者신성영

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 08:26:33