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

8 篇文章 1 订阅

想要在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的方式进行传递.
--------------------- 
作者:Donnie2016 
来源:CSDN 
原文:https://blog.csdn.net/donnie88888888/article/details/53435556 
版权声明:本文为博主原创文章,转载请附上博文链接!

 

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值