Question

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.

Was it helpful?

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.

OTHER TIPS

This is correct C++/CLI function definition:

[DllImport("user32.dll")]         
static int SetForegroundWindow(IntPtr hWnd);

Agree with David Heffernan, there is no point to use PInvoke in C++/CLI - just call API directly. PInvoke is for C#/VB .NET developers.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top