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

How to get string from managed c++ dll (using wrapper class) in c#

本文关键字:包装类 字符串 获取 c++dll      更新时间:2023-10-16

我使用非托管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
}