Skip to content

Instantly share code, notes, and snippets.

@domgetter
Created July 28, 2014 09:29
Show Gist options
  • Save domgetter/7e5dbcb25ac47ac0b471 to your computer and use it in GitHub Desktop.
Save domgetter/7e5dbcb25ac47ac0b471 to your computer and use it in GitHub Desktop.
Segmentation Fault example from waveOutProc callback for waveOutOpen windows multimedia function.
require 'ffi'
class HWAVEOUT < FFI::Struct
layout :i, :int
end
class WAVEFORMATEX < FFI::Struct
def initialize
self[:wFormatTag] = 1
self[:nChannels] = 1
self[:nSamplesPerSec] = 44100
self[:wBitsPerSample] = 16
self[:cbSize] = 0
self[:nBlockAlign] = (self[:wBitsPerSample] >> 3) * self[:nChannels]
self[:nAvgBytesPerSec] = self[:nBlockAlign] * self[:nSamplesPerSec]
end
layout(
:wFormatTag, :ushort,
:nChannels, :ushort,
:nSamplesPerSec, :ulong,
:nAvgBytesPerSec, :ulong,
:nBlockAlign, :ushort,
:wBitsPerSample, :ushort,
:cbSize, :ushort
)
end
class WAVEHDR < FFI::Struct
layout(
:lpData, :pointer,
:dwBufferLength, :ulong,
:dwBytesRecorded, :ulong,
:dwUser, :ulong,
:dwFlags, :ulong,
:dwLoops, :ulong,
:lpNext, :pointer,
:reserved, :ulong
)
end
class Sound
extend FFI::Library
ffi_lib :winmm
callback :waveOutProc, [:pointer, :uint, :ulong, :ulong, :ulong], :void
attach_function :waveOutOpenCallback, :waveOutOpen, [:pointer, :uint, :pointer, :waveOutProc, :ulong, :ulong], :uint
attach_function :waveOutOpenNull, :waveOutOpen, [:pointer, :uint, :pointer, :ulong, :ulong, :ulong], :uint
WaveOutProc = Proc.new do |hwo, mMsg, dwCallback, dwParam1, dwParam2|
puts mMsg
return
end
end
hWaveOut = HWAVEOUT.new
wfx = WAVEFORMATEX.new
puts "waveOutOpen returns 0 (no error) if I don't use the callback form"
puts Sound.waveOutOpenNull(hWaveOut.pointer, -1, wfx.pointer,0,0,0)
puts "but if I use a callback, the moment it returns from the callback, there is a seg fault"
puts "note that the code inside the callback runs, as I am puts-ing the mMsg which is 955"
puts "for WOM_OPEN which tells us the device was opened."
puts "this is on ruby 1.9.3p484 (2013-11-22) [i386-mingw32] running 1.9.3 x86-mingw32 on"
puts "Windows 7"
puts Sound.waveOutOpenCallback(hWaveOut.pointer, -1, wfx.pointer,Sound::WaveOutProc,0,0x30000)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment