修改传递给C dll c#的char数组

时间:2012-07-04 06:52:38

标签: c# c string dll marshalling

我只是试图从C#传递缓冲区到C dll,让C func填充缓冲区,然后在C#代码中用缓冲区做一些事情。但我正在缓冲区中回收垃圾。这是C:

    extern "C" __declspec( dllexport )      
    int  cFunction(char *plotInfo, int bufferSize) 
    {
        strcpy(plotInfo, "text");
        return(0);
    }

C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
namespace ConsoleApplication1
{
class Program
{
 [DllImport("mcDll.dll",
     CallingConvention = CallingConvention.Cdecl, CharSet=CharSet.Unicode)]

    public static extern int cFunction( StringBuilder theString, int bufferSize);
    static void Main(string[] args)
    {
        StringBuilder s = new StringBuilder(55);
        int result = cFunction( s, 55);
        Console.WriteLine(s);
    }
   }
}

1 个答案:

答案 0 :(得分:2)

Native函数使用ANSI字符进行操作。只需从导入定义中删除CharSet.Unicode即可。