想要在C#和C++之间进行字符串传递会涉及到两件事情:
1.C#的string和C++的字符串首指针要怎么对应.
2.字符串分为ANSI和UNICODE.
C++ 头文件接口:
-
-
-
- extern "C" __declspec(dllexport) char* __stdcall EncryptString(char* in_string);
-
- extern "C" __declspec(dllexport) TCHAR* __stdcall EncryptStringW(TCHAR* in_string);
-
- extern "C" __declspec(dllexport) int __stdcall Sum(int a, int b);
C++ 实现部分:
-
-
- #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", 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());
-
-
- IntPtr ip = EncryptStringW("Hello 您好.");
- string strIP = Marshal.PtrToStringUni(ip);
- Console.WriteLine(strIP);
-
-
- ip = EncryptString("Hello 您好.");
- strIP = Marshal.PtrToStringAnsi(ip);
- Console.WriteLine(strIP);
-
- Console.ReadLine();
- }
- }
为了C#能方便调用,在C++中特别将调用方式设置为:__stdcall . (关于调用方式的详细说明,请进 传送门). 否则需要在C#里指定 [DllImport("FilePolice", CallingConvention = CallingConvention.Cdecl)].
另外,由于我们的字符串中会使用到中文,所以一般使用Unicode的方式进行传递.