【发布时间】:2015-06-05 17:41:17
【问题描述】:
我使用非托管 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:\Projects\program10\program10\hexclass.cpp"
#include "D:\Projects\program10\program10\hexclass.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 转换没有太多经验
请建议我如何改进我的代码以获得更好的内存管理,因为我必须一个接一个地传递大量系统文件并获取它们的十六进制代码
【问题讨论】:
标签: c# c++ c unmanaged managed