简体   繁体   中英

C++ dll within c#

I have C++ DLL as below

#include "stdafx.h"


extern "C" __declspec(dllexport)double Add(double a, double b);


extern double Add(double a, double b) 
{ 
    return a + b; 
} 

n here m trying to link this DLL with my C# app

using System.Text;

using System.Runtime.InteropServices; 

namespace test
{

    class Program

    {

        [DllImport("DLL.dll", CallingConvention = CallingConvention.Cdecl)]

        public static extern double Add(double a, double b);  


        static void Main(string[] args)

        {




            Console.WriteLine(Add(1.0, 3.0)); // error here


            Console.ReadLine(); 

        }
    }
}

m getting error:

"Unable to load DLL 'DLL.dll': The specified module could not be found. (Exception from HRESULT: 0x8007007E)"

please help me out ...how can i link c++ dll with c# ?

The calling convention determines how function parameters are placed on the stack prior to a function invocation, and how they are removed (caller vs. callee) when the function returns. You can find out much more about this in about a million StackOverflow questions, or goto here and read up a little.

Regarding placement of the DLL within reach of the C# (aka .NET) application you're writing, I'm afraid I cannot comment on that except to say general DLL's must be in your lib-search path (PATH in Windows) the current directory, or the kernel's home directory (generally c:\\windows\\system32. Do NOT copy files to system32, btw. just setup your application to "run from" the directory where your DLL is residing and you should be fine. There are exceptions to this, and configuration settings that can radically alter this, but were I you i'd stick with simple for now. Complex can always come later.

You will either need to plant the dll in the same location as the C# exe or pack the dll inside the exe. The first option is simple enough. For the second option, check out Embedding DLL's into .exe in in Visual C# 2010

you got this error because DLL.dll wasn't in your Debug/Release Folder,

as far as i know visual studio doesn't know how to copy those files to your output folder manualy.

add the dll file to your C# solution

and then on files properties set build action to content and set copy to output directory to copy if newer this will automate the copying

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM