[英]Using C++ DLL in C# project
我有一個C ++ DLL,它必須集成在一個C#項目中。
我想我找到了正確的方法,但是調用dll會給我這個錯誤:System.BadImageFormatException:試圖加載一個格式不正確的程序。 (HRESULT異常:0x8007000B)
這是dll中的函數:
extern long FAR PASCAL convert (LPSTR filename);
這是我在C#中使用的代碼
namespace Test{
public partial class Form1 : Form
{
[DllImport("convert.dll", SetLastError = true)]
static extern Int32 convert([MarshalAs(UnmanagedType.LPStr)] string filename);
private void button1_Click(object sender, EventArgs e)
{
// generate textfile
string filename = "testfile.txt";
StreamWriter sw = new StreamWriter(filename);
sw.WriteLine("line1");
sw.WriteLine("line2");
sw.Close();
// add checksum
Int32 ret = 0;
try
{
ret = convert(filename);
Console.WriteLine("Result of DLL: {0}", ret.ToString());
}
catch (Exception ex)
{
lbl.Text = ex.ToString();
}
}
}}
有關如何進行此操作的任何想法?
非常感謝,弗蘭克
嘗試將您的C#代碼從AnyCPU切換到x86(在“屬性”對話框中)。
導出的函數使用PASCAL
調用約定,在Windows中與stdcall
相同。 .Net運行時需要知道這一點,因此修改您的C#方法簽名如下:
[DllImport("convert.dll", SetLastError = true, CallingConvention=CallingConvention.StdCall)]
static extern Int32 convert([MarshalAs(UnmanagedType.LPStr)] string filename);
嘗試在從DLL導出的函數中使用__stdcall
(或WINAPI
或APIENTRY
)。
涉及的兩個主要步驟是
1-創建C ++ DLL
在視覺工作室
**New->Project->Class Library** in c++ template Name of project here is first_dll in visual studio 2010. Now **declare your function as public** in first_dll.h file and write the code in first_dll.cpp file as shown below.
Check **Project-> Properties -> Configuration/General -> Configuration Type**
this option should be **Dynamic Library(.dll)** and build the solution/project now.
first_dll.dll文件在Debug文件夾中創建
2-在C#項目中鏈接它
打開C#項目
Rightclick on project name in solution explorer -> Add -> References -> Browse to path
where first_dll.dll is created and add the file
在C#項目的頂部添加此行
Using first_dll;
現在可以在某些函數中使用下面的語句訪問文件
double var = Class1.sum(4,5);
我將VS2010中創建的C ++項目.dll鏈接到VS2013中創建的C#項目。 它運作良好。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.