tags:

views:

896

answers:

3

I'm trying to get into COM interop

So, there is a simple example:

  SpeechLib.SpVoice voice = new SpVoice();
  voice.Speak("Hello sucker!",SpeechVoiceSpeakFlags.SVSFDefault);

Of course I have to add reference to %windir%\system32\speech\common\sapi.dll before, and VS will add Interop.SpeechLib.dll to the project folder, and now I have to distribute this 200kb library with my simple 4kb application.

Can I use [DllImport] instead of adding reference, because in most cases speech library is already presented on a client's computer?

Could you show me how to rewrite the code above using DllImport technique?

A: 

If I understand, you are trying to do late binding. I suggest you to use Reflection. Check this post: http://www.c-sharpcorner.com/UploadFile/samhaidar/LateBindingWithReflection09122005053810AM/LateBindingWithReflection.aspx

Hope it helps

+1  A: 

You are unlikely to be able to use [DllImport] instead of "Add Reference" if the Speech API is a COM API.

[DLLImport] is used for invoking unmanaged, Win32 DLL's, while "Add Reference" is a short cut for running tlbimp.exe (typelib import) to enable .NET to COM interop.

You can learn more about COM Interop here and DllImportAttribute here. Pinvoke.net is a great site for finding DllImport signatures.

Zach Bonham
A: 

[DllImport] is not what you want. However, the interop library you see when when you add a COM reference is just a convenience; you're always free to write your own instead.

The easiest way to see this is to use Reflector to disassemble the COM interop assembly (Interop.SpeechLib.dll in your case) into a tree of source files.

The interop assembly will contain .NET declarations for all of the COM types in the typelibrary, which is usually what you want, but if you only need a small subset of that, you can get rid of the bits you don't need.

If you don't like having a second DLL dependency, you can even add the source files generated by Reflector to your existing project, thereby compiling them into your assembly.

anelson