4

I have a couple of methods imported from a native .dll, using the following syntax:

internal static class DllClass {
    [DllImport("Example.dll", EntryPoint = "ExampleFunction")]
    public static extern int ExampleFunction([Out] ExampleStruct param);
}

Now, because I specified param as [Out], I would expect at least one of the following snippets to be valid:

ExampleStruct s;
DllCass.ExampleFunction(s);

ExampleStruct s;
DllCass.ExampleFunction([Out] s);

ExampleStruct s;
DllCass.ExampleFunction(out s);

However, none of them works. The only way I found to make it work was by initializing s.

ExampleStruct s = new ExampleStruct();
DllCass.ExampleFunction(s);

I have managed to fix that by rewriting the first snippet to the following code, but that feels kinda redundant.

internal static class DllClass {
    [DllImport("Example.dll", EntryPoint = "ExampleFunction")]
    public static extern int ExampleFunction([Out] out ExampleClass param);
}

I've read What's the difference between [Out] and out in C#? and because the accepted answer states that [Out] and out are equivalent in the context, it left me wondering why it didn't work for me and if my "solution" is appropriate.

Should I use both? Should I use only out? Should I use only [Out]?

Community
  • 1
  • 1
rmobis
  • 26,129
  • 8
  • 64
  • 65

2 Answers2

2

The OutAttribute determines the runtime behavior of the parameter, but it has no impact at compile time. The out keyword is required if you want to use compile-time semantics.

Using just the out keyword will change the runtime marshaling, so the OutAttribute is optional. See this answer for more info.

Community
  • 1
  • 1
user1620220
  • 1,295
  • 8
  • 15
  • Ok, so, assuming I don't want compile-time semantics, will the code with initialization actually work? (That is, will I get a correct value in `param`?) And, suppose I do, will it work if I keep both `out` and `[Out]`? – rmobis Oct 30 '14 at 12:54
  • I believe the answer is yes to both, provided the external function is written correctly to expect an `out` parameter. – user1620220 Oct 30 '14 at 12:57
0

Are you initializing it to a value inside the function? That's where the requirement comes in: out parameters must be assigned to at least once within the function which declares the parameter.

Platinum Azure
  • 45,269
  • 12
  • 110
  • 134
  • 1
    Since this is an external dll, I doubt the compiler knows what's inside the function. – user1620220 Oct 30 '14 at 12:46
  • Even if I weren't, wasn't this supposed to give me an error on the function definition instead of on the call? – rmobis Oct 30 '14 at 12:48
  • 2
    How does this answer the question? It seems to me that this should be posted as a comment, since it is only asking for clarification – default Oct 30 '14 at 12:51