如何在c#中从托管c ++ dll(使用包装类)获取字符串

时间:2015-04-01 06:55:08

标签: c# c++ c unmanaged managed

我使用非托管dll完成了这项操作但使用托管dll时遇到了一些困难。

我想将一个字符串传递给我的托管c ++包装器类,它处理它并返回修改后的字符串

c ++ dll的目的是返回一个文件的十六进制代码(后来修改它以在dll中执行一些复杂的任务),我把它作为一个字符串传递给了这个approcach我使用了托管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转换没有太多经验

请建议我如何改进我的代码以获得更好的内存管理,因为我必须逐个传递大量系统文件并获取其十六进制代码

1 个答案:

答案 0 :(得分:0)

取决于

// hexcode logic

是,在C#中实现它可能更好/更容易,而忘记编组。

如果你真的需要编组从C ++到C#的字符串,这个主题可能会对你有所帮助:How to marshall c++ char* to C# string using P/INVOKE(代码在这里)

基本上只是从你的本机代码中构建一个本机DLL,如果只需要一个字符串,你就可以从C#中调出它而不是拥有中间托管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
}