代码之家  ›  专栏  ›  技术社区  ›  Frank

C++DLL在C++项目中的应用

  •  6
  • Frank  · 技术社区  · 15 年前

    我得到了一个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();
            }
        }
    }}
    

    你有什么办法继续吗?

    谢谢, 弗兰克

    4 回复  |  直到 15 年前
        1
  •  4
  •   Oleg    15 年前

    尝试使用 __stdcall WINAPI APIENTRY )在从DLL导出的函数中。

        2
  •  4
  •   Josip Medved    15 年前

        3
  •  4
  •   Frank Bollack    15 年前

    PASCAL 调用约定,在Windows中与 stdcall . .Net运行时需要知道这一点,因此请修改C方法签名,如下所示:

    [DllImport("convert.dll", SetLastError = true, CallingConvention=CallingConvention.StdCall)]
    static extern Int32 convert([MarshalAs(UnmanagedType.LPStr)] string filename);
    
        4
  •  0
  •   Croko    10 年前

    涉及的两个主要步骤是

    1——创建一个C++ DLL

    在visual studio中

    **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.
    

    Header File

    Cpp File

    Check **Project-> Properties -> Configuration/General -> Configuration Type** 
    this option should be **Dynamic Library(.dll)** and build the solution/project now.
    

    第一个dll.dll 文件创建于 调试文件夹

    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 
    

    Using first_dll; 
    

    现在,可以在某些函数中使用下面的语句访问该文件

    double var = Class1.sum(4,5);
    

    我将VS2010中创建的C++项目DLL链接到VS2013中创建的C项目。效果很好。