如何从c#中的托管c++dll(使用包装类)获取字符串
How to get string from managed c++ dll (using wrapper class) in c#
我使用非托管dll完成了这项工作,但在使用托管dll时遇到了一些困难。
我想把一个字符串传递给我的托管c++包装类,该类处理它并返回修改后的字符串
c++dll的目的是返回文件的十六进制代码(后来修改它以在dll中执行一些复杂的任务),我将其作为字符串传递,为此,我使用了托管的c++dll而不是非托管的。
我的c++类如下:
using namespace std;
//main function - entry point of program __declspec(dllexport)
const char* hexclass:: getfilename(char* filename)
{
//to open file
ifstream::pos_type size;
string virusScanStatus;
char* fileAccessError;
string errorDes ="Exception has Occured With Current File Operation";
//hexcode logic goes here
fileAccessError = new char[errorDes.size()];
errorDes.copy(fileAccessError,errorDes.size());
return fileAccessError;
}
我的c++包装器类如下所示:头文件包括这里的c++文件(代码没有显示)
using namespace System;
namespace CWrapperHexValue {
public ref class cWrapperHexValue
{
public:
cWrapperHexValue();
const char* hexValue;
const char* getHexValue(char* fileName);
private:
hexclass* pHexClass;
};
}
我的包装器类如下:
// This is the main DLL file.
#pragma once
#include "stdafx.h"
#include "CWrapperHexValue.h"
#include "D:Projectsprogram10program10hexclass.cpp"
#include "D:Projectsprogram10program10hexclass.h"
CWrapperHexValue::cWrapperHexValue::cWrapperHexValue()
{
pHexClass = new hexclass();
}
const char* CWrapperHexValue::cWrapperHexValue::getHexValue(char* fileName)
{
hexValue= pHexClass -> getfilename(fileName);
return hexValue;
}
最后我的c#代码发送文件名如下:
//my c++ dll name is CWrapperHexValue
CWrapperHexValue.cWrapperHexValue objHexClass = new CWrapperHexValue.cWrapperHexValue();
byte[] fileNameBytes = Encoding.ASCII.GetBytes(fileNameForHexScan);
unsafe
{
fixed (byte* p= fileNameBytes)
{
sbyte* sp = (sbyte*)p;
sbyte* returnSp = objHexClass.getHexValue(sp);
}
}
现在我如何将returnSp值作为字符串或任何其他更好的传递和获取字符串的方法返回,请提供有用的代码,因为我对c++/c#cli转换没有太多经验
请建议我如何改进我的代码以更好地管理内存,因为我必须一个接一个地传递大量的系统文件,并获得它们的十六进制代码
取决于
// hexcode logic
是的,在C#中实现它并忘记封送处理可能会更好/更容易。
如果你真的需要将字符串从C++封送到C#,这个主题可能会对你有很大帮助:如何使用p/INVOKE(代码在这里)将C++char*封送到C#字符串
基本上,只需从本机代码中构建一个本机DLL,如果只需要一个字符串,则可以从C#中pinvoke它,而不是使用中间托管C++类。
在内存管理方面,如果您可以将六进制代码逻辑移到C#中,这将消除封送字符串的需要,并可能节省一些处理,但更重要的是,调试起来不那么痛苦。也就是说,你为什么不能这样做?
C#
public void SomeFunction()
{
string filepath = "foo.bar"
string hexVal = HexCodeLogicInManaged(filepath);
... other code ...
}
private string HexCodeLogicInManaged(string filepath)
{
// hexcode logic converted from native to managed
}
相关文章:
- C++类字符串类型的迭代器
- 简化在 Pybind11 中为 C++ 模板类生成包装类:模板声明不能出现在块范围内
- C++-用与被包装数据相同的语法构造包装类
- C++-用和结构相同的语法围绕结构构造包装类
- C++泛型包装类,它为某些函数添加了额外的处理
- 如何减少大量包装类的实现代码?
- 在 C++ 中为 C 样式对象创建一个透明包装类
- C++ 一个自定义类字符串,将其分配给 C 样式字符串
- 如何将包装类的对象用作包装函数中的参数
- 这->...在模板包装类中必需
- 无法理解包装类的构造函数的声明
- 标准向量之上的 C++11 包装类
- 编写安全包装类以管理用户定义对象的指针
- 重构现有包装类,以使用与包装器本身相同的构造函数参数包装 T
- 包装类设计和依赖注入
- 提升 Python 导入失败,未定义包装类的符号
- 类字符串和嵌套向量C
- 简单包装类与智能指针
- C# 使用包装类中的字符串参数调用 C++ 方法
- 如何从c#中的托管c++dll(使用包装类)获取字符串