Dom*_*tal 27 c# dll interop call dllimport
我是C#的新手,我正在努力学习使用DLL.我正在尝试将我的对象包装在DLL中,然后在我的程序中使用它.
public class Foo // its in the DLL
{
public int ID;
public void Bar()
{
SomeMethodInMyProgram();
}
}
Run Code Online (Sandbox Code Playgroud)
所以我尝试将其打包到DLL但我不能,因为编译器不知道SomeMethodInMyProgram()是什么.
我想用它像:
class Program // my program, using DLL
{
static void Main(string[] args)
{
Foo test = new Foo();
test.Bar();
}
}
Run Code Online (Sandbox Code Playgroud)
Tom*_*kel 41
取决于什么类型的DLL.这是用.NET构建的吗?如果它是非托管代码,那么这里是一个例子,否则Rob的答案将起作用.
非托管C++ DLL示例:
using System;
using System.Runtime.InteropServices;
Run Code Online (Sandbox Code Playgroud)
您可能需要使用DllImport
[DllImport(@"C:\Cadence\SPB_16.5\tools\bin\mpsc.dll")]
static extern void mpscExit();
Run Code Online (Sandbox Code Playgroud)
要么
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
public static extern int MessageBox(IntPtr hWnd, String text, String caption, uint type);
Run Code Online (Sandbox Code Playgroud)
然后每个人都这样调用:
// a specific DLL method/function call
mpscExit();
// user32.dll is Microsoft, path not needed
MessageBox(new IntPtr(0), "Test", "Test Dialog", 0);
Run Code Online (Sandbox Code Playgroud)
我在这里参加聚会迟到了,但是我把这个答案留给了像我一样拔头发的人。所以基本上,面对这个问题时,我没有 VS IDE 的奢侈。我试图使用 csc 通过 cmdline 编译代码。为了引用一个 dll,只需将编译器标志 /r:PathToDll/NameOfTheDll 添加到 csc。
该命令看起来像
csc /r:PathToDll/NameOfTheDll /out:OutputExeName FileWhichIsReferencingTheDll.cs
在FileWhichIsReferencingTheDll.cs 中添加using namespace AppropriateNameSpace;访问函数(通过调用 class.functionName 如果是静态的或通过创建类的对象并在对象上调用函数)。
您需要在运行时实际将 DLL 加载到应用程序中,即 DLL 的动态部分。您还需要定义 DLL 中的函数的头文件,以便您的编译知道已定义了哪些函数。我这里的知识是基于 C++ 的,所以这对于 C# 是如何工作的我不确定,但它会是这样的......
| 归档时间: |
|
| 查看次数: |
80536 次 |
| 最近记录: |