'CS0212 Error using dll with unsafe code: You can only take the address of an unfixed expression inside of a fixed statement initializer
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) ?
Solution 1:[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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
