Skip to content

Instantly share code, notes, and snippets.

@odan
Last active January 3, 2024 09:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save odan/e44221ab63bd18db2c828d43b02d62e1 to your computer and use it in GitHub Desktop.
Save odan/e44221ab63bd18db2c828d43b02d62e1 to your computer and use it in GitHub Desktop.

PHP FFI - Using a C++ DLL with C bindings with MinGW-64

Requirements

  • MinGW-64

Setup

On Windows:

Example DLL

To specify C linkage, specify extern "C" for your function declarations.

File: example.cpp

extern "C" __declspec( dllexport ) int foo();

int foo() {
    return 123;
}

Compilation

g++ -shared -s -mwindows -Wl,--subsystem,windows -o example.dll example.cpp

The -Wl,--subsystem,windows isn't really necessary, but it's just conventional that DLLs have the Windows GUI subsystem specified in their PE header. Also note the -s switch is used to strip symbols from the DLL - you will probably want to do this only for release builds.

Optional: To specify a input directory for header files, just add the -I c:\path\to\include as parameter:

PHP FFI Usage

<?php

use FFI;

$ffi = FFI::cdef(
    'int foo();',
    'example.dll'
);

var_dump($ffi->foo());

Output:

int(123)

PHP FFI - Using a C++ DLL with C bindings

Requirements

  • Visual Studio 2022 Community Edition (free)
  • The C and C++ SDK of Visual Studio

Setup

Add C:\Program Files\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.38.33130\bin\Hostx64\x64 to the system PATH enviornemnt variable.

This is the location of cl.exe

cl.exe ist the C / C++ compiler for the console.

Example dll

To specify C linkage, specify extern "C" for your function declarations.

File: example.cpp

extern "C" __declspec( dllexport ) int foo();

int foo() {
    return 123;
}

Compilation

Open "cmd" and run: "C:\Program Files\Microsoft Visual Studio\2022\Community\VC\Auxiliary\Build\vcvars64.bat" to register the env variables.

In the same cmd window run the following command to compile the cpp file into a dll.

cl.exe /D_USRDLL /D_WINDLL example.cpp /link /DLL /OUT:wrapper.dll

PHP FFI Usage

<?php

use FFI;

$ffi = FFI::cdef(
    'int foo();',
    'example.dll'
);

var_dump($ffi->foo());

Output:

int(123)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment