将LPTSTR参数传递给DLL会在C ++项目中产生访问冲突

时间:2014-12-21 17:41:56

标签: c++ dll

我在未记录的DLL中调用函数来解压缩文件。

标头声明/分配的方式一定有错,但无法弄清楚出了什么问题。

VS 2010中的项目字符集是Unicode。

可以使用下面的代码段从C#成功调用DLL函数(但我需要使它在c ++中工作):

[DllImport("unpacker.dll", EntryPoint = "UnpackFile", PreserveSig = false)]
internal static extern IntPtr UnpackFile(byte[] file, int fileSize,
[MarshalAs(UnmanagedType.LPWStr)] StringBuilder header, int headerSize);

如果我取消注释移动一个标题,则弹出一个Acccess Violation。该函数也返回0,它在C#中没有。

有什么想法吗?

VC ++ 2010项目中的代码:

// unpacker.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <windows.h> 
#include <fstream>

using namespace std;

typedef void* (*UnpackFile)(unsigned char*, int, LPTSTR, int);

int _tmain(int argc, _TCHAR* argv[])
{
    LPTSTR header; 
    //Move this and get a access violation on the _UnpackFile(filetounpack... line

    static unsigned char *filetounpack; //Buffer to byte array with the file to unpack
    int filelen; //variable to store the length of the file
    HINSTANCE dllHandle; // Handle to DLL
    UnpackFile _UnpackFile; // Function pointer
    ifstream filetoread; //Stream class to read from files
    static LPTSTR header2;  //Buffer for the header 2nd


    filetoread.open ("c:/projects/testfile.bin", ios::in | ios::binary|ios::ate); 
    filelen = filetoread.tellg(); //read the length
    filetounpack = new unsigned char [filelen]; //allocate space

    filetoread.seekg (0, ios::beg); //set beginning
    filetoread.read ((char *)filetounpack, filelen); //read the file into the buffer
    filetoread.close(); //close the file

    dllHandle  = LoadLibrary(_T("unpacker.dll"));

    _UnpackFile = (UnpackFile)GetProcAddress(dllHandle, "UnpackFile");

    //header = new _TCHAR[filelen]; //Allocate memory for header
    header2 = new _TCHAR[filelen]; //Allocate memory for header

    //Access violation reading location 0xffffffffffffffff!!!
    void* tmp = _UnpackFile(filetounpack ,filelen ,header2 ,filelen); 

    delete[] filetounpack;
    delete[] header;
    delete[] header2;

    FreeLibrary(dllHandle); 
    return 0;

}

1 个答案:

答案 0 :(得分:5)

 typedef void* (*UnpackFile)(unsigned char*, int, LPTSTR, int);

这与您的C#声明的CallingConvention属性不匹配。 C#的默认值是StdCall,本机C ++项目的默认值是__cdecl。修正:

 typedef void* (__stdcall * UnpackFile)(unsigned char*, int, LPTSTR, int);

请记住,错误检查在C ++中永远不是可选的,你真的需要检查LoadLibrary()和GetProcAddress()是否成功。在C#中自动,而不是在C ++中。两个函数在失败时都返回NULL。

相关问题