-1

I have a DLL in C++/CLI which is of the form :

bool func (String^, unsigned long, LPDWORD)

I wish to call this function from within C# code, where LPDOWRD is exposed as uint*.

While I can easily put the final parameter within an unsafe context, I would rather avoid it. Is there any way I can pass on the final parameter without using an unsafe context?

user1173240
  • 1,455
  • 2
  • 23
  • 50

2 Answers2

3

Since the DLL is already in C++/CLI, I think you shouldn't use the LPDWORD type at all! The point of C++/CLI is to provide a bridge between managed and unmanaged code, so instead, declare that method as you would in C#.

As your question is written, there's no way to provide an exact answer, because we don't know what that LPDWORD represents:

  • It could be that it's an optional parameter, allowing the caller to specify either a value or null.
  • It could be a required parameter that gets updated by the called method. Example: Pass a pointer to a buffer size, the integer pointed to gets modified to be the number of bytes used within the buffer.
  • It could be an output parameter that gets updated by the called method. (This is very similar to the previous, except that the value of the memory pointed to initially doesn't mean anything.)
  • It could be a pointer to the beginning of an array.
  • There's probably others I'm not thinking of.

Each of these is slightly different, and would be handled differently from C#.

Here's how I would re-write that method, depending on how it's used.

public ref class CallTypes
{
public:
    bool func_optInt(String^ s, UInt64 ul, Nullable<UInt32> optInt) { return false; }
    bool func_refInt(String^ s, UInt64 ul, UInt32% refInt) { return false; }
    bool func_outInt(String^ s, UInt64 ul, [Out] UInt32% outInt) { return false; }
    bool func_arrayInt(String^ s, UInt64 ul, array<UInt32>^ arrayInt) { return false; }
};

When viewed in C#, here's how those methods look (as viewed in Visual Studio's Object Browser from C#):

enter image description here

David Yaw
  • 27,383
  • 4
  • 60
  • 93
0

You can use ref/out modifiers or IntPtr type:

[return: MarshalAs(UnmanagedType.Bool)]
private extern static bool func(string str, ulong num, ref uint dword);

or

[return: MarshalAs(UnmanagedType.Bool)]
private extern static bool func(string str, ulong num, IntPtr dword);
György Kőszeg
  • 17,093
  • 6
  • 37
  • 65