我的 c ++ dll 文件中有一个很大的字符串,我需要将其作为字节数组传递给C#,我不知道该怎么做!
我知道我可以在C#中使用此功能:
字符串结果= System.Text.Encoding.UTF8.GetString(bytearray);
我需要知道如何将字符串转换为utf8数组并将其发送到C#,以及如何在C#应用程序中获取字符串:)
有关此问题的更多信息:
我不知道如何像swprintf到StringBuilder一样将字节数组从C ++解析为C#。
这是我的问题的示例代码:
C ++代码:
#include "stdafx.h"
#include <iostream>
#include <cstdio>
#include <fstream>
BOOL APIENTRY DllMain( HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
extern "C" __declspec(dllexport) void __stdcall sendasbyte(char* byte_to_send)
{
std::ifstream file_t("testfile.txt");
std::string Read_test_file((std::istreambuf_iterator<char>(file_t)),
std::istreambuf_iterator<char>());
///// NEED TO SEND Read_test_file as byte array to C# HERE :
// <-------- CODE AREA --------->
}
以下是C#代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.InteropServices;
namespace minimal_project_testapp
{
class Program
{
[DllImport("minimal_project_test.dll", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Unicode)]
private static extern void sendasbyte(byte[] get_String_Byte);
private static byte[] data_from_cpp;
static void Main(string[] args)
{
sendasbyte(data_from_cpp);
string result = System.Text.Encoding.UTF8.GetString(data_from_cpp);
Console.WriteLine(result);
Console.ReadLine();
}
}
}
然后是testfile.txt:https://textuploader.com/dvvbb
答案 0 :(得分:-1)
这是做到这一点的方法清晰完美:D
1>将您的 c ++函数更改为此:
extern "C" __declspec(dllexport) char* __stdcall test_int()
{
std::ifstream file_t("testfile.txt");
std::string Read_test_file((std::istreambuf_iterator<char>(file_t)),
std::istreambuf_iterator<char>());
int size_of_st = Read_test_file.length();
std::string test1 = std::to_string(size_of_st);
char* cstr = new char [size_of_st];
std::strcpy(cstr, Read_test_file.c_str());
return cstr;
}
2> 不要忘记添加#define _CRT_SECURE_NO_WARNINGS
3>将 Dllimport 添加到您的C#应用程序
[DllImport("minimal_project_test.dll", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Unicode)]
private static extern IntPtr test_int();
4>并最终在您需要的任何地方使用它:
IntPtr _test_from_Cpp = test_int();
int _test_char_count = <Enter Length of your string>;
byte[] _out_char_value = new byte[_test_char_count];
Marshal.Copy(_test_from_Cpp, _out_char_value, 0, _test_char_count);
string final_string = System.Text.Encoding.UTF8.GetString(_out_char_value);
轰!有用 !!! ;)