Search code examples
c#c++-clitranslationdllimportstatic-classes

Translate DllImport from static member of static class in C# console app to member of C++ CLR console app


I have the following and I can't shift the error surrounding the DllImport

#include "stdafx.h"
#include <msclr/auto_gcroot.h>

using namespace System;
using namespace System::Diagnostics;
using namespace System::Runtime::InteropServices;
using namespace System::Threading;
using namespace System::Collections::Generic;
using namespace System::Text;

namespace WinFlix
{
    class FlickWin
    {
        [DllImport("user32.dll")]
        extern "C" bool SetForegroundWindow(IntPtr hWnd);

I've been tranlating this class from C# where it was a static class, which is not available in C++.NET. My new C++ project is of type "CLR Console Application".

I get

error C2059: syntax error : 'string'

and

error C2238: unexpected token(s) preceding ';'

both referring to that 'extern "C"' line.

I've searched my previous work and while I am competent with C++/CLI I've not had to call down into WinAPI functions like this before. Those two errors are all that are beating me :-/

TBH, this thing exhausted my patience and I deleted it, could go back and re-create it but I preferred fixing my C# instead. Help appreciated for future reference though.


Solution

  • The extern "C" is inappropriate for DllImport. That's the source of the error.

    The problem is that you are declaring your P/invoke inside a class. As far as I can tell, in C++ they are meant to be declared as free functions outside any classes. I've not found much documentation for P/invoke from C++/CLI, probably because P/invoke is not needed from C++/CLI.

    You don't need P/invoke with C++/CLI because the compiler can include standard C++ header files and link against native libraries. Just include windows.h and call the Win32 APIs with no futher effort. That's one of the best points of C++/CLI.