C#调用C++生成的dll,传字符串类型,返回字符串类型

1.创建一个C++的动态链接库

  头文件.h

#include
#include
#include
#include
using namespace std; 

extern "C" MATHFUNCSDLL_API BOOL  __stdcall CallString(char *str);
extern "C" MATHFUNCSDLL_API BOOL  __stdcall CallStringInAndOut(char *input, char *output);

源文件.cpp

BOOL  __stdcall CallString(char *str) {

    string ppp = "HelloWorld!";
    //const int len = ppp.length();
    strcpy(str, ppp.c_str());
    return 1;
}

BOOL  __stdcall CallStringInAndOut(char *input, char *output) {
    string ppp = input;
    ppp += "123456";
    //const int len = ppp.length();
    strcpy(output, ppp.c_str());
    return 1;
}

2.C#下调用

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace CSDllTest
{
    class Program
    { 

        [DllImport("DllTest.dll", EntryPoint = "CallString")]
        public static extern int CallString(ref byte str);

        [DllImport("DllTest.dll", EntryPoint = "CallStringInAndOut")]
        public static extern int CallStringInAndOut(ref byte input, ref byte output);

        static void Main(string[] args)
        { 

            byte[] s = new byte[1024];
            int t = CallString(ref s[0]);//用字节数组接收动态库传过来的字符串
            string strGet = System.Text.Encoding.Default.GetString(s, 0, s.Length); //将字节数组转换为字符串

            string input = "HelloWorld";
            byte[] byteInput = Encoding.UTF8.GetBytes(input);
            byte[] byteOutput = new byte[1024];
            t = CallStringInAndOut(ref byteInput[0], ref byteOutput[0]);//用字节数组接收动态库传过来的字符串
            strGet = System.Text.Encoding.Default.GetString(byteOutput, 0, byteOutput.Length); //将字节数组转换为字符串
            Console.ReadKey();
        }  

    }
}
 

你可能感兴趣的:(C#)