2

i have an unmanaged dll written in C++ which has a one simple function.

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

and exported function is

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

Then i have a C# project that imports this dll. What I want to do is creating a class that imports dll and creating instances from another class.

class DllClass
    {
        public int classval;

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

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

And in the Forms Application

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");
    }
}

but all tree instances are the same. I want independent instances. Is this possible?

1 Answers1

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");
}
David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490