C#调用C++的Dll(参数和返回值為char* TCHAR*)

想要在C#和C++之间进行字符串传递会涉及到两件事情:

1.C#的string和C++的字符串首指针要怎么对应.  

2.字符串分为ANSI和UNICODE.


C++ 头文件接口:

//FilePolice.h

//參數和返回值為Ansi
extern "C" __declspec(dllexport) char* __stdcall EncryptString(char* in_string);
//參數和返回值為Unicode
extern "C" __declspec(dllexport) TCHAR* __stdcall EncryptStringW(TCHAR* in_string);
//參數和返回值為int
extern "C" __declspec(dllexport) int __stdcall Sum(int a, int b);

C++ 实现部分:

// FilePolice.cpp 

#include "stdafx.h"
#include "FilePolice.h"  

TCHAR* __stdcall EncryptStringW(TCHAR* in_string)
{
	return in_string;
}

char* __stdcall EncryptString(char* in_string)
{
	return in_string;
}

int __stdcall Sum(int a, int b)
{
	return a + b;
}

C# 调用部分:

class Program
{
    [DllImport("FilePolice")]
    public static extern int Sum(int a, int b);

    ////[DllImport("FilePolice", CallingConvention = CallingConvention.Cdecl)]
    ////[DllImport("FilePolice", CallingConvention = CallingConvention.StdCall)]
    ////UnmanagedType.LPStr 為 ANSI
    ////UnmanagedType.LPWStr 為 Unicode
    [DllImport("FilePolice", CharSet = CharSet.Unicode)]
    public static extern IntPtr EncryptStringW([MarshalAs(UnmanagedType.LPWStr)]string inString);

    [DllImport("FilePolice", CharSet = CharSet.Ansi)]
    public static extern IntPtr EncryptString([MarshalAs(UnmanagedType.LPStr)]string inString);

    static void Main(string[] args)
    {
        int result = Sum(1, 2);
        Console.WriteLine(result.ToString());

        //Unicode
        IntPtr ip = EncryptStringW("Hello 您好.");
        string strIP = Marshal.PtrToStringUni(ip);
        Console.WriteLine(strIP);

        //Ansi
        ip = EncryptString("Hello 您好.");
        strIP = Marshal.PtrToStringAnsi(ip);
        Console.WriteLine(strIP);

        Console.ReadLine();
    }
}

为了C#能方便调用,在C++中特别将调用方式设置为:__stdcall . (关于调用方式的详细说明,请进 传送门). 否则需要在C#里指定 [DllImport("FilePolice", CallingConvention = CallingConvention.Cdecl)].

另外,由于我们的字符串中会使用到中文,所以一般使用Unicode的方式进行传递.



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