使用 Dllimport 将非常大的字符串作为字节数组从 C++ 传递到 C#

passing a very large string as byte array from C++ to C# with Dllimport

我的 我的 c++ dll 文件中有一个非常大的字符串,我需要将它作为字节数组传递给 C#,但我不知道该怎么做!

我知道我可以在 C# 中使用这个函数:

string result = System.Text.Encoding.UTF8.GetString(bytearray);

我需要知道如何将我的字符串转换为 utf8 数组并将其发送到 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

这是如何做到这一点 清晰完美 :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);

轰!有用 !!! ;)