登录 用户中心() [退出] 后台管理 注册
   
您的位置: 首页 >> SoftHub关联区 >> 主题: [u3d]C#接收C++动态库返回字符串char*,在C#端如何接收并得到正确的字符串     [回主站]     [分站链接]
[u3d]C#接收C++动态库返回字符串char*,在C#端如何接收并得到正确的字符串
clq
浏览(308) - 2019-04-06 16:46:34 发表 编辑

关键字: u3d

[2019-04-06 16:47:28 最后更新]
[u3d]C#接收C++动态库返回字符串char*,在C#端如何接收并得到正确的字符串

https://blog.csdn.net/qq_22889875/article/details/78670172

u3d 下也可用

最近调用动态库传数据,发现C#接收C++动态库返回字符串char*,在C#端设置对应类型为string无法接收到正确值,最后想到在C#端先用字节数组接收返回的字符串,然后再将字节数组转换为对应的字符串,数据接收终于正确
首先打开VS2012,新建项目->Visual C++,选择Win32项目,如图选择dll
这里写图片描述
新建项目的名字为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;
}

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11

在dlltest.h中加入:

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

    1

运行环境为debug模式,点击生成解决方案,在debug文件下可看到生成了dlltest.dll,这就是动态库文件。
这里写图片描述

打开VS2012,新建Visual C#控制台应用程序,命名为dlltestC
新建类文件Class1.cs,启动程序,运行空项目(debug模式),生成exe文件,打开exe所在目录,将之前生成的dll复制到该目录下,如图。
这里写图片描述
然后在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);

    }
}

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17

最后在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);

        }
    }
}

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21

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




总数:0 页次:1/0 首页 尾页  
总数:0 页次:1/0 首页 尾页  


所在合集/目录



发表评论:
文本/html模式切换 插入图片 文本/html模式切换


附件:



NEWBT官方QQ群1: 276678893
可求档连环画,漫画;询问文本处理大师等软件使用技巧;求档softhub软件下载及使用技巧.
但不可"开车",严禁国家敏感话题,不可求档涉及版权的文档软件.
验证问题说明申请入群原因即可.

Copyright © 2005-2020 clq, All Rights Reserved
版权所有
桂ICP备15002303号-1