2

我有一个用 C++ 编写的非托管 dll,它有一个简单的功能。

int temp =0;
int func1(void)
{
    return temp +=2;
}

和导出的功能是

UNMANAGED_DLL1_API int recepret(void)
{
    return func1();
}

然后我有一个导入这个 dll 的 C# 项目。我想要做的是创建一个导入 dll 的类并从另一个类创建实例。

class DllClass
    {
        public int classval;

        [DllImport("unmanaged_dll1.dll", EntryPoint = "recepret", CharSet = CharSet.Unicode)]
        public static extern int recepret();

        public int func1()
        {
            return recepret();
        }
}

并在表格应用程序中

public partial class Form1 : Form
{
    DllClass dll1 = new DllClass();
    DllClass dll2 = new DllClass();
    DllClass dll3 = new DllClass();
private void button1_Click(object sender, EventArgs e)
    {
        richTextBox1.AppendText( "dll1 " +  dll1.func1().ToString()+ "\r\n");
    }

    private void button2_Click(object sender, EventArgs e)
    {
        richTextBox1.AppendText("dll2 " + dll2.func1().ToString() + "\r\n");
    }

    private void button3_Click(object sender, EventArgs e)
    {
        richTextBox1.AppendText("dll3 " + dll3.func1().ToString() + "\r\n");
    }
}

但所有树实例都是相同的。我想要独立的实例。这可能吗?

4

1 回答 1

1

You have a global variable. There's just one instance of it per module instance. And there's one instance of your native DLL module per process. Using a global variable is not the solution here.

If you want to have a different variable associated with each button click, you'll need to create a separate variable for each.

It would make much more sense for the variables to be owned by the C# code.

Your C++ code would look like this:

void func1(int &value)
{
    value +=2;
}

Then in the C# you call it like this:

[DllImport("unmanaged_dll1.dll")]
public static extern void func1(ref int value);

....

int button1counter = 0;

private void button1_Click(object sender, EventArgs e)
{
    dll1.func1(ref button1counter);
    richTextBox1.AppendText( "dll1 " +  button1counter.ToString()+ "\r\n");
}
于 2013-04-14T19:48:43.953 回答