问题
I'm new to C# and I'm trying to learn to usage of DLLs. I'm trying to wrap my objects in a DLL, and then use it in my program.
public class Foo // its in the DLL
{
public int ID;
public void Bar()
{
SomeMethodInMyProgram();
}
}
So I try to pack this to a DLL but I can't, because compiler doesn't know what the SomeMethodInMyProgram() is.
I would like to use it like:
class Program // my program, using DLL
{
static void Main(string[] args)
{
Foo test = new Foo();
test.Bar();
}
}
回答1:
Add the DLL via the solution explorer - right click on references --> add reference then "Browse" to your DLL - then it should be available.
回答2:
Depends on what type of DLL. Is this built in .NET ? if it is unmanaged code then here is an example otherwise the Answer from Rob will work.
Unmanaged C++ dll example:
using System;
using System.Runtime.InteropServices;
You may need to use DllImport
[DllImport(@"C:\Cadence\SPB_16.5\tools\bin\mpsc.dll")]
static extern void mpscExit();
or
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
public static extern int MessageBox(IntPtr hWnd, String text, String caption, uint type);
Then each of those are called like this:
// a specific DLL method/function call
mpscExit();
// user32.dll is Microsoft, path not needed
MessageBox(new IntPtr(0), "Test", "Test Dialog", 0);
回答3:
you need to actually load the DLL into your application at run time, thus the Dynamic part of DLL. You also need the header file that defines what functions are in the DLL so your compile knows what functions have been defined. My knowledge here is based on C++ so how this works for C# I am not to sure, but it will be something like that...
回答4:
I am late to the party here but am leaving this answer for someone pulling his/her hair out like me. So basically, I did not have the luxury of VS IDE when facing this issue.I was trying to compile the code via cmdline using csc. In order to reference a dll, just add the compiler flag /r:PathToDll/NameOfTheDll to csc.
The command would look like
csc /r:PathToDll/NameOfTheDll /out:OutputExeName FileWhichIsReferencingTheDll.cs
In FileWhichIsReferencingTheDll.cs add using namespace AppropriateNameSpace;
to access the functions (by calling class.functionName if static or by creating an object of the class and invoking the function on the object).
来源:https://stackoverflow.com/questions/5010957/call-function-from-dll