locked
How to pass parameters of Type HANDLE from C# to C++ DLL

    Question

  • Hi, I have a question about calling C++ functions from C#.

    The situation is: I have a C++ DLL. I want to use this DLL to develop a C# program. That means I want to call C++ DLL functions from C# code.

    I have read some articles and messages about how to call C++ DLL functions from C# code. But my task is harder. The C++ function I will call needs a parameter of type HANDLE. I can't find type HANDLE in C#. I guess Microsoft doesn't let programmers have low-level control over program, so we can't get a file's HANDLE in C#.

    How can I solve this problem?

    Another question is: is it true we can't use C++ classes in C# code? I got this point from some messages but I am not sure. After the C++ DLL function can be called from C# code, it must be wrapped into a C# class ( and even namespace) using [DllImport]. But we can't wrap C++ classes into a C# class. So we can't use C++ classes this way. We must write some functions to instantiate C++ classes and then wrap these functions into a C# class, then we can call these functions in C# code. Is it true?

     

    Thanks.

    Friday, June 30, 2006 6:31 PM

Answers

  • 1) To pass HANDLE use IntPtr type. You can see, for example, that Control.Handle Property has IntPtr type.

    2) C++ classes cannot be used direcctly by C#, only functions (API). The best way to use C++ code is using C++/CLI wrapper which calls unmanaged C++ classes directly and exposes .NET interface to C# client.

    Other way is writing C wrapper for C++ classes and using it from C#. But using C++/CLI is better.

    Friday, June 30, 2006 6:51 PM
  • FileStream.Handle, it's an IntPtr and appears to contains the handle that the CreateFile() API returns.  Careful messing with it or you might confuse the stream code.

    Friday, June 30, 2006 7:23 PM
    Moderator

All replies

  • 1) To pass HANDLE use IntPtr type. You can see, for example, that Control.Handle Property has IntPtr type.

    2) C++ classes cannot be used direcctly by C#, only functions (API). The best way to use C++ code is using C++/CLI wrapper which calls unmanaged C++ classes directly and exposes .NET interface to C# client.

    Other way is writing C wrapper for C++ classes and using it from C#. But using C++/CLI is better.

    Friday, June 30, 2006 6:51 PM
  • Thanks.

    Another question is: how to get a file's HANDLE in C#? If I open a file (or a database) in C#, can I get HANDLE? is it the same with HANDLE in C++?

     

    Friday, June 30, 2006 7:05 PM
  • FileStream.Handle, it's an IntPtr and appears to contains the handle that the CreateFile() API returns.  Careful messing with it or you might confuse the stream code.

    Friday, June 30, 2006 7:23 PM
    Moderator