-1

我有 2 个 DLL。一个是 PrimaryDLL.dll,另一个是 DLLWrap.dll。PrimaryDLL 有一个对象,一个名为 DiversifyKeyset 的函数,它在类构造函数中像这样贴花:

static PRIMARYDLL_API std::string DiversifyKeyset(std::string Key1, std::string Key2, std::string Key3);

这是定义的方法:

    std::string tKeyset::DiversifyKeyset(std::string Key1, std::string Key2, std::string Key3)
{
    tKeyset* keyset = new tKeyset();

    keyset ->Key1 = "12345678";
    keyset ->Key2 = "23456789";
    keyset ->Key3 = "34567890";

    //return keyset --eventually I want to return this
    return 0;

}

我的 DLLWrap.dll 在它的 .cpp 文件中调用这个函数:

cout << "Here is what is returned:  " <<
firstDllLayer::tKeyset::DiversifyKeyset(a,b,c) << endl;

现在这一切都编译好了,库也建好了。当我调用 C# 代码调用第二个 DLLWrap.dll 时,我的错误出现了。我收到错误:

Attempted to read or write protected memory. This is often an indication that other memory is corrupt.

所以我一直在绞尽脑汁想为什么这不起作用。我承受着很大的压力,但似乎找不到我收到此内存写入错误的原因。

所以为了帮助我提供我的代码。

我的 C++ PrimaryDLL.h 文件:

#pragma once

#include "stdafx.h"
#include <string>
#include <stdexcept>

extern "C"{

#ifdef PRIMARYDLL_EXPORT
    #define PRIMARYDLL_API __declspec(dllexport) 
#else
    #define PRIMARYDLL_API __declspec(dllimport)  
#endif



namespace firstDllLayer
{

class tKeyset
{


public:
    tKeyset();
    std::string Key1;
    std::string Key2;
    std::string Key3;
    tKeyset(std::string _key1, std::string _key2, std::string _key3);
    static PRIMARYDLL_API std::string DiversifyKeyset(std::string Key1, std::string Key2, std::string Key3);


};

tKeyset::tKeyset()
{
    Key1 = "";
    Key2 = "";
    Key3 = "";
}
tKeyset::tKeyset(std::string _Key1, std::string _Key2, std::string _Key3)
{
    Key1 = _Key1;
    Key2 = _Key2;
    Key3 = _Key3;
}


}
}

这是 PrimaryDll.cpp 文件:

// PrimaryDll.cpp : Defines the exported functions for the DLL application.
//
#include "stdafx.h"
#include "PrimaryDll.h"
#include <stdexcept>
#include <string>
using namespace std;
namespace firstDllLayer
{
    tKeyset* MasterKeyset = new tKeyset("1234","5678","0910");
    std::string tKeyset::DiversifyKeyset(std::string Key1, std::string Key2, std::string Key3)
{
    tKeyset* keyset = new tKeyset();
    keyset ->Key1 = "12345678";
    keyset ->Key2 = "23456789";
    keyset ->Key3 = "34567890";
    //return Keyset; -eventually I would like to return this
    return 0;
}
}

这是我的 DLLWrap.h 文件:

#pragma once

#include "stdafx.h"
#include "Primary.h"
#include <stdexcept>
#include <string>
extern "C"{
#ifdef DLLWRAPDLL_EXPORT
    #define DLLWRAP_API __declspec(dllexport) 
#else
    #define DLLWRAP_API __declspec(dllimport)  
#endif
namespace MyFunc
{
    class MyCall
        {
        public:
            static DLLWRAP_API std::string DiversifyKeysetCall(std::string a,std::string b,std::string c);
    };
}
}

DLLWrap.cpp 文件:

// DLLWrap.cpp : Defines the exported functions for the DLL application.
//


#include "stdafx.h"
#include "PrimaryDll.h"
#include <stdexcept>
#include "DLLWrap.h"
#include <iostream>
#include <string>

using namespace std;

namespace MyFunc
{
    std::string MyCall::DiversifyKeysetCall(std::string a,std::string b,std::string c)
    {
            /*cout << "Here is what is returned:  " <<
                firstDllLayer::tKeyset::DiversifyKeyset(a,b,c) << endl;

            return 0;*/
        cout << "Here is what is returned:  " <<
                firstDllLayer::tKeyset::DiversifyKeyset(a,b,c) << endl;

            return 0;           
    }
}

最后是 C# Program.cs 文件:

// Marshal.cs
using System;
using System.Runtime.InteropServices;
class PlatformInvokeTest
{    public class DllHelper
    {
        [DllImport(@"C:\Users\user\Documents\Visual Studio 2010\Projects\KeyDll\Debug\DLLWrap.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "?DiversifyKeysetCall@MyCall@MyFunc@@SA?AV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@V34@00@Z")]

        public static extern string DiversifyKeysetCall(string a, string b, string c);
    }
    static void Main()
    {    
        try
        {
            DllHelper.DiversifyKeysetCall("1234","5678","0910");           
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
        }
}

在我的 PrimaryDLL.cpp 文件中,我最终想返回该对象,但因为它在如何引用指针以及何时离开时非常混乱:

return keyset; 

未评论我收到无法从对象类型转换为字符串类型的错误。

因此,请任何帮助将不胜感激为什么我会收到“尝试读取或写入受保护的内存。这通常表明其他内存已损坏”错误。

此致。

4

2 回答 2

1
std::string tKeyset::DiversifyKeyset(...) {
  return 0;
}

这调用 std::string(const char*) 构造函数,传递一个 NULL 指针。这是非法的。

于 2013-07-16T20:48:46.820 回答
1

一般来说,在 c++ dll 中创建一个对象并将其交回 c# 是一个坏主意。内存的所有权成为一个问题。字符串是可以的,因为它们通过从 c 内存到 c# 拥有的内存进行编组。

我建议您通过分别传递三个字符串并在 C# 中构建您的键集对象来简化整个事情。

另一种选择是将您的键集对象展平为二进制字节数组。然后有一个自定义函数,当你把它重新展平成一个对象时。

这是我以前做过的

[DllImport("Helper.dll", CharSet = CharSet.Auto)]
private static extern bool GetStuff(
    [MarshalAs(UnmanagedType.LPStr)] StringBuilder inputString,
    byte[] outputBuffer, 
    UInt32 outputSize,
    ref UInt32 outputFinalSize);

public static void DoStuff(string inputString)
{
    int buffSize = 4000;
    byte[] buff = new byte[buffSize];
    StringBuilder inputString = new StringBuilder();
    inputString.Append(blobs);
    UInt32 size = 0;

    if (!GetStuff(inputString, buff, (uint)buffSize, ref size) || size == 0)
    {
        //ERROR
    }

    when it comes back i just do

    StringBuilder outputString;
    for (uint i = 0; i < outputFinalSize; i++)
    {
        outputString.Append((char)buff[i]);
    }

    outputString.toString();
}

c signatrue 看起来像这样

extern "C" __declspec(dllexport) bool GetStuff(char* inputString, char* outputBuffer, UInt32 outputSize, UInt32& outputFinalSize);

请注意,我也使用字符串生成器来传递字符串,您可能不需要...如您所见,我在 c# 端分配了所有内容,因此我不必担心 c++ 的内存管理,所有内容都在当函数完成时,c++ 应该被释放。

你的电话应该看起来像

private static extern bool DiversifyKeysetCallAndRetrunFlatBuffer(
    [MarshalAs(UnmanagedType.LPStr)] StringBuilder inputStringA,
    [MarshalAs(UnmanagedType.LPStr)] StringBuilder inputStringB,
    [MarshalAs(UnmanagedType.LPStr)] StringBuilder inputStringC,
    byte[] outputBuffer, 
    UInt32 outputSize, 
    ref UInt32 outputFinalSize);

{
    std::string str1(inputStringA);
    std::string str2(inputStringB);
    std::string str3(inputStringC);
    KeySet key = DiversifyKeyset(str1, str2, str3);

    outputFinalSize = key.SerializeToBuffer(outputBuffer, outputSize);

    if (outputFinalSize == 0) 
    {
        return false;
    }
    return true;
}

int KeySet::SerializeToBuffer(char* buffer, size_t bufferSize)
{
    //We are going to fill the buffer like so "key1|key2|key3"

    size_t totalSize = Key1.size() + Key2.size() + Key3.size() + 4;
    if (bufferSize < totalSize)
    {
        return 0; // buffer too small
    }
    char* bufferCurr = buffer;


    memcpy(bufferCurr, Key1.c_str(), Key1.size());
    bufferCurr += Key1.size();
    bufferCurr[0] = '|';
    bufferCurr++;

    memcpy(bufferCurr, Key2.c_str(), Key2.size());
    bufferCurr += Key2.size();
    bufferCurr[0] = '|';
    bufferCurr++;

    memcpy(bufferCurr, Key3.c_str(), Key3.size());
    bufferCurr += Key3.size();
    bufferCurr[0] = '\0';
    return totalSize;
}

最后在 c# 方面,您可以将缓冲区转换为字符串并按 | 进行拆分。获取所有 3 个键,然后创建具有 3 个字符串的 ac# KeySet 对象。

于 2013-07-16T21:00:33.097 回答