我在解壓文件的未公開DLL中調用函數。將LPTSTR參數傳遞給DLL會導致C++項目中的訪問衝突
標題聲明/分配的方式必須有錯誤,但無法弄清楚發生了什麼問題。
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違反彈出的頭。該函數也返回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;
}
嘗試聲明函數指針爲'__stdcall':'typedef void *(__stdcall * UnpackFile)(unsigned char *,int,LPTSTR,int);' –
好的!調整爲typedef void *(__stdcall * UnpackFile)(unsigned char *,int,LPTSTR,int);但仍然沒有喜樂。其實如果我取消註釋標題行。 Text Visualizer中的標題變量已更改。 header2變量正在填充正確的數據..任何想法? –
你確定你正在構建一個Unicode版本嗎?如果你改變了'UnpackFile'聲明並且創建了第三個參數'LPWSTR'而不是'LPTSTR',程序是否還在編譯? –