Method: WIN32OLE#initialize

Defined in:
lib/win32ole-pr.rb

#initialize(server = nil, host = nil) ⇒ WIN32OLE

Creates a new Win32::OLE server object on host, or the localhost if no host is specified. The server can be either a Program ID or a Class ID.

Examples:

# Program ID (Excel)
ole = Win32::OLE.new('Excel.Application')

# Class ID (Excel)
ole = Win32::OLE.new('{00024500-0000-0000-C000-000000000046}')

– TODO: explain numeric server and host behavior.



309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
# File 'lib/win32ole-pr.rb', line 309

def initialize(server=nil, host=nil)
  WIN32OLE.ole_initialize()

  @pDispatch = nil

  return self if server.nil?

  if server.is_a?(Numeric)
    ole_set_member(server)
    return self
  end

  if host
    return ole_create_dcom(server, host)
  end

  clsid = 0.chr * 16
  serverw = multi_to_wide(server)

  hr = CLSIDFromProgID(serverw, clsid)

  if hr != S_OK
    hr = CLSIDFromString(serverw, clsid)
  end

  if hr != S_OK
    raise WIN32OLERuntimeError, "unknown OLE server: '#{server}'"
  end

  ptr = 0.chr * 4

  hr = CoCreateInstance(
      clsid,
      nil,
      CLSCTX_INPROC_SERVER | CLSCTX_LOCAL_SERVER,
      IID_IDispatch,
      ptr
  )

  if hr != S_OK
    error = "failed to create WIN32OLE object from '#{server}'"
    raise WIN32OLERuntimeError, error
  end

  ole_set_member(ptr.unpack('L').first)

  self
end