2

The (incomplete) snippet

unsafe class MainWindow
{
     ...
     IntPtr somePtr = IntPtr.Zero;
     unsafe private void Click(object sender, RoutedEventArgs e)
     {
         NamespaceFromReferencedUnsafeDll.SomeFunction(&somePtr)
     }
     ...
}

}

Is supposed to call SomeFunction from a managed Dll with unsafe code, to set the pointer somePtr, but results in the compiler error

CS0212: You can only take the address of an unfixed expression inside of a fixed statement initializer

According to this answer, the fixed keyword has to be used in some way, but

fixed(IntPtr somePtr = IntPtr.Zero);

didn't help.

How can I fix this (no pun intended) ?

Oblomov
  • 8,953
  • 22
  • 60
  • 106
  • 2
    Pass `out somePtr`, then no unsafe code is needed. The `extern` declaration may need to be adjusted likewise. Note that if you are intending to actually call the function rather than treat it as an opaque value things get more complicated, and you need things like `Marshal.GetDelegateForFunctionPointer`. – Jeroen Mostert Mar 30 '22 at 07:15

1 Answers1

1

The problem was the signature of

SomeFunction 

in the referenced unsafe dll.

After changing

public static unsafe uint SomeFunction(IntPtr* somePtr)

to

public static unsafe uint SomeFunction(out IntPtr somePtr)

the snippet

class MainWindow
{
     ...
     IntPtr somePtr = IntPtr.Zero;
     private void Click(object sender, RoutedEventArgs e)
     {
            NamespaceFromReferencedUnsafeDll.SomeFunction(out somePtr)
     }
     ...
}

compiles without errors and works at runtime.

Oblomov
  • 8,953
  • 22
  • 60
  • 106
  • 1
    Note that `unsafe` can be removed everywhere (in this part of the code at least), since passing `out IntPtr` is perfectly safe in managed code. It's also generally good practice to restrict `unsafe` to specific blocks rather than apply it to entire methods or classes -- ideally the unsafe bits are wrapped with code that is safe. – Jeroen Mostert Mar 30 '22 at 09:26
  • Thanks, please review the updated version of the answer. – Oblomov Mar 30 '22 at 12:46