我想继续通过TCP通信将从C++(而不是C++/CLI)接收到的数据发送到C#。
我写了这样的代码:
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"));
此代码按预期传递一个字符串和一个字符串数组,并显示一个消息框。
我想继续通过TCP通信将从C++(而不是C++/CLI)接收到的数据发送到C#。
1条答案
按热度按时间sg24os4d1#
xx.h
xx.cpp
C#语言