c# 调用DLL StringBuilder 乱码


C++中的代码 定义了一个iReadIdentityCard 供C# 调用
#define DL1_API extern "C" _declspec(dllexport)
#include "dl1.h"
#include <cstring>
  
int iReadIdentityCard(char *pOutInfo, char *pErrMsg){
 
    char *B = "姓名|男|汉族|1988-10-23|地址|513029198810230011|发行机关|20991010|20991010|adasdadsadadsa|";
    strcpy(pOutInfo, B);
    return 0;
}
//---------------------============
c# 调用
using System;
using System.Text;
using System.Runtime.InteropServices;

namespace ConsoleApplication1
{
    class Class1
    {
        [DllImport("SC_ID.dll", EntryPoint = "iReadIdentityCard", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)]
        public static extern int iReadIdentityCard(StringBuilder pOutInfo, StringBuilder pErrMsg);
    }
}



namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            StringBuilder a=new StringBuilder(1024);
            StringBuilder b=new StringBuilder();
            int x = Class1.iReadIdentityCard(a, b);
              
             Console.WriteLine(x+">>"+a+">>");
             Console.ReadKey();
        }
    }
}

输出 的a 是乱码

参考,来源: C# 调用C++ dll 返回char*调用方式(StringBuilder乱码)_weixin_34130269的博客-CSDN博客 // CDLLDemo.cpp : 定义 DLL 应用程序的导出函数。//#include "stdafx.h"#include "string.h"#include <stdio.h>#include <time.h>extern "C" __declspec(dllexport)int ParseBaliseMsg2(const un... https://blog.csdn.net/weixin_34130269/article/details/92928145
1.用StringBuilder接收Char参数 需要定义为[MarshalAs(UnmanagedType.LPStr)]StringBuilder,否则就是乱码。
2.用ref byte memory接收Char
参数 不能使用ref IntPtr方式接收,否则返回值一直为空。
3.使用返回值Char* 直接使用IntPtr方式接收即可。

调用到了DLL的方法 获取了int x的返回值,

img