陷入了非常天真的问题。我有两个项目,一个在C++,另一个在C#。想法是使用C++项目作为一些C库的包装器。并在C#中执行实际逻辑。
传递值类型非常方便。但是对于引用类型,没有使用、、不安全的或DllImport属性,我就有困难的时间。
C++
Cryptoki.Wrapper.h文件
using namespace System;
#pragma comment(lib, "legacy_stdio_definitions.lib")
namespace CryptokiWrapper {
public ref class CryptokiInit
{
public:
char* TESTString(char* test);
double TESTDouble(double test);
};
}Cryptoki.Wrapper.cpp文件
#include "stdafx.h"
#include "Cryptoki.Wrapper.h"
using namespace std;
using namespace CryptokiWrapper;
char* CryptokiInit::TESTString(char* test)
{
char* r = test;
return r;
}
double CryptokiInit::TESTDouble(double test)
{
unsigned long int r = test;
return r;
}C#码
using System;
using System.Runtime.InteropServices;
using CryptokiWrapper;
namespace CallCryptoki
{
class Program
{
//[MarshalAs(UnmanagedType.LPTStr)]
//public String msg = "Hello World";
static void Main(string[] args)
{
CryptokiInit ob = new CryptokiInit();
//This Works
doubled d = ob.TESTDouble(99);
//But having hard time accepting the char* reference
//or sending string as refrence without using unsafe
// like
string text = "Hello World!";
string res = (*something*)ob.TESTString((*something*)text);
}
}
}是否有任何类型的铸造(即某事).有什么地方我可以轻松地执行这个动作吗。(只有引用传输就足够了,然后我可以构建字符串或对象)
就像在另一个函数上一样,使用double作为参数和返回类型。
虽然上面的示例只提到字符串,但希望将其理解为概念,以便我可以为两个项目之间的任何引用类型(即C#和C++)编写互操作。
提前感谢您的帮助!
发布于 2016-04-03 09:42:49
首先,这不是普通的C++,而是C++/CLI --这主要是为托管/非托管代码互操作性而设计的。
C++/CLI函数可以使用.NET的字符串类型,如下所示:
System::String^ TESTString(System::String^ test);^的意思是托管引用,把它看作是*的托管等价。
现在,要在纯C++中使用字符串数据,您有两个选择:
const char*,请执行以下操作:
#包含
msclr::interop::marshal_context ctx;testCStr = ctx.marshal_as(test);// testCStr在ctx超出作用域时被释放
这将复制字符串数据,因为内存表示需要从2个字节的标准字符更改为单个字符。const wchar_t*的形式直接访问内存。您需要预先插入字符串,这样它就不会被GC移动。
#包括
pin_ptr testCStr = PtrToStringChars(test);// testCStr的行为与const wchar_t*一样
做,而不是,用这种方式修改字符串数据。要将字符串发送回托管端,可以使用marshal_as<System::String^>(yourCString)或调用gcnew System::String(yourCString);
https://stackoverflow.com/questions/36383541
复制相似问题