Search code examples
dllmingwxaudio2

Mingw, XAudio2, and GetProcAddress failing


I am trying to use XAudio2 with Mingw. Since I couldn't figure out what I'm suppose to to do to get Mingw to link XAudio2, I thought I would try to use XAudio2 purely through a dll loading. But the following code failed to find XAudio2Create with GetProcAddress.

#include <windows.h>

static HMODULE xaudio2 = NULL;

int WINAPI WinMain(HINSTANCE hinstance, HINSTANCE hprevinstance, LPSTR lpcmdline, int ncmdshow) {
    xaudio2 = LoadLibraryA("XAudio2_2.dll");
    if (xaudio2 == NULL) {
        MessageBox(NULL, L"LoadLibrary failed", 0, 0);
    }

    void* fnc = GetProcAddress(xaudio2, "XAudio2Create");
    if (fnc == NULL) {
        MessageBox(NULL, L"GetProcAddress failed", 0, 0);
    }

    return 0;
}

Solution

  • I figured out you have to go through COM and CoCreateInstance(). Something like

    #include <windows.h>
    #include <stdio.h>
    #include <XAudio2.h>
    
    int WINAPI WinMain(HINSTANCE hinstance, HINSTANCE hprevinstance, LPSTR lpcmdline, int ncmdshow) {
        WAVEFORMATEX format;
        format.wFormatTag = 1;
        format.nChannels = 1;
        format.nSamplesPerSec = 44100;
        format.nAvgBytesPerSec = 44100;
        format.nBlockAlign = 1;
        format.wBitsPerSample = 8;
        format.cbSize = 0;
    
        CoInitializeEx(NULL, COINIT_MULTITHREADED);
    
        IXAudio2* pXAudio2 = NULL;
        IXAudio2SourceVoice* source = NULL;
        IXAudio2MasteringVoice* master = NULL;
    
        HRESULT hr;
        if ( FAILED(hr = XAudio2Create( &pXAudio2, 0, XAUDIO2_DEFAULT_PROCESSOR ) ) ) {
            MessageBox(0, L"hi", L"hi", 0);
        }
    
        if ( FAILED(hr = pXAudio2->CreateMasteringVoice(&master ) ) ) {
            MessageBox(0, L"hi", L"hi", 0);
        }
    
        if ( FAILED(hr = pXAudio2->CreateSourceVoice(&source, &format) ) ) {
            MessageBox(0, L"hi", L"hi", 0);
        }
    
        char str[30];
    
        float freq = 0.0;
        source->GetFrequencyRatio(&freq);
        sprintf(str, "%f", freq);
            MessageBoxA(0, str, str, 0);
    
        UINT32 OperationSetCounter = 0;
        UINT32 OperationID = UINT32(InterlockedIncrement(LPLONG(&OperationSetCounter)));
    
        if ( FAILED(hr = source->SetFrequencyRatio(1.1,OperationID ) ) ) {
            MessageBox(0, L"hi", L"hi", 0);
        }
    
        if ( FAILED(hr = pXAudio2->CommitChanges(OperationID ) ) ) {
            MessageBox(0, L"hi", L"hi", 0);
        }
    
    
    
        float freq2 = 0.0;
        source->GetFrequencyRatio(&freq2);
        sprintf(str, "%f", freq2);
        MessageBoxA(0, str, str, 0);
    
        Sleep(2000);
        float freq3 = 0.0;
        source->GetFrequencyRatio(&freq3);
        sprintf(str, "%f", freq3);
        if (freq3 != 1.0) {
            MessageBoxA(0, str, str, 0);
        }
    
        source->Start(0);
        return 0;
    }