发新帖

[C#/ASP.NET] [C/VC/C++] C#接收C++动态库返回字符串CHAR*,在C#端如何接收并得到正确的字符串

零下一度 2022-12-2 788

1、动态库代码部分

新建项目的名字为dlltest,新建头文件dlltest.h,在源文件dlltest.cpp中加入如下代码:

#include "stdafx.h"
#include "dlltest.h"
char s[20]="您好hahaha";
int __stdcall test(char* str)
{
    char attr[1024];
    memset(attr,0,sizeof(attr));
    memcpy(attr,s,sizeof(s));
    memcpy(str,attr,sizeof(attr));
    return 1;
}

在dlltest.h中加入:

extern "C" _declspec(dllexport) int __stdcall test(char* str);

2、C#引用部分代码

引用动态库文件,Class1.cs中加入如下代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.InteropServices;
namespace dlltestC
{
    public class Class1
    {
        [DllImport("dlltest.dll", EntryPoint = "test")]
        public extern static int test(ref byte str);
    }
}

Program.cs中加入:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace dlltestC
{
public class Program
{
static void Main(string[] args)
{
byte[] s = new byte[1024];
int t = Class1.test(ref s[0]);//用字节数组接收动态库传过来的字符串
string strGet = System.Text.Encoding.Default.GetString(s, 0, s.Length); //将字节数组转换为字符串
Console.WriteLine(strGet);
}
}
}

运行该程序,输出:您好hahaha


@灰信网


最新回复 (0)
返回
零下一度
主题数
928
帖子数
0
注册排名
1