如何编组多字节字符集C#

时间:2012-09-24 19:14:31

标签: c# c++ string marshalling

我需要调用一个使用C#中的多字节字符集的函数(c / c ++)。但我不知道如何将其编组为多字节。有谁知道如何将结果转换为字符串?

C#:

[DllImport("essentials.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
        public static extern System.IntPtr GetFiles(string filedir, string path);

        [STAThread]
        static void Main()
        {
            string filedir = @"C:\Users\Ruben\Documents\School\*";
            string path = @"C:\Users\Ruben\Documents\School\";
            System.IntPtr pointer = GetFiles(filedir, path);
            string files = Marshal.PtrToStringAnsi(pointer); // nothing
        }

C ++

extern "C"
{
    __declspec(dllexport) char* GetFiles(char* filedir, char* path)
    {
        string filedir2 = filedir;
        string path2 = path;
        string files = GetFiles2(filedir2, path2);
        char* Rfiles = new char[files.length() + 1];
        strcpy_s(Rfiles, files.length() + 1, files.c_str());
        return Rfiles;
    }
}

2 个答案:

答案 0 :(得分:0)

有关MSDN的信息:Default Marshaling for Strings

答案 1 :(得分:0)

首先需要编组C#字符串,试试这个:

[DllImport("essentials.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
    public static extern System.IntPtr GetFiles
        ([MarshalAs(UnmanagedType.AnsiBStr)]string filedir,
        [MarshalAs(UnmanagedType.AnsiBStr)]string path);