Mutual issue of passing structure by ref, null to pointer and IntPtr

Colleagues,

Preamble. My question is more about best practices. I know one workaround. This is the first time I have to deal with interop in C #, while Ive written quite a bit of code in C and C ++.

I need to call the function open by an unmanaged DLL twice. The function takes a pointer to a structure as an argument. The first time I need to pass a pointer null. 2nd time I need to pass a pointer to an instance of the structure.

The function has 6 parameters, so the following are simplified declarations that work for the purpose of this issue. (I can post specifics if someone is interested.) Here is the 1st version of the ad:

[DllImport("setupapi.dll", CharSet = CharSet.Auto, SetLastError = true)]
   static extern bool foo(ref NEEDED_STRUCT_TYPE sDataStruct);

I like it because it is strictly printed for NEEDED_STRUCT_TYPE. But in order to be able to pass a null pointer, I had to change the declaration to

[DllImport("setupapi.dll", CharSet = CharSet.Auto, SetLastError = true)]
   static extern bool foo(IntPtr sDataStruct);

Now I can pass a pointer IntPtr.Zeroto null, but this parameter is no longer strongly typed. In this situation, is there a way to have both: a strongly typed parameter and the ability to skip the null pointer?

Any suggestion, understanding or link is really appreciated!

Greetings
- Nick

+3
source share
1 answer

- API, ( ..), , - DllImport, . , , API.

+3

Source: https://habr.com/ru/post/1782232/


All Articles