Contrary to the answers here, you DON'T need to worry about encoding if the bytes don't need to be interpreted!
Like you mentioned, your goal is, simply, to "get what bytes the string has been stored in".
(And, of course, to be able to re-construct the string from the bytes.)
For those goals, I honestly do not understand why people keep telling you that you need the encodings. You certainly do NOT need to worry about encodings for this.
Just do this instead:
static byte[] GetBytes(string str)
{
byte[] bytes = new byte[str.Length * sizeof(char)];
System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
return bytes;
}
// Do NOT use on arbitrary bytes; only use on GetBytes's output on the SAME system
static string GetString(byte[] bytes)
{
char[] chars = new char[bytes.Length / sizeof(char)];
System.Buffer.BlockCopy(bytes, 0, chars, 0, bytes.Length);
return new string(chars);
}
As long as your program (or other programs) don't try to interpret the bytes somehow, which you obviously didn't mention you intend to do, then there is nothing wrong with this approach! Worrying about encodings just makes your life more complicated for no real reason.
Additional benefit to this approach: It doesn't matter if the string contains invalid characters, because you can still get the data and reconstruct the original string anyway!
It will be encoded and decoded just the same, because you are just looking at the bytes.
If you used a specific encoding, though, it would've given you trouble with encoding/decoding invalid characters.
I found the solution myself. To replicate the settings that Visual Studio uses with tlbimp you simply need to use the /out and /namespace flags.
The out flag is used to prefix "Interop." on the generated file and the namespace flag is used to set the default namespace to the name of the COM assembly.
e.g.
tlbimp /out:Interop.MyCom.dll /namespace:MyCom MyCom.dll
Best Solution
Oh... found it after looking at the folder where TLBIMP belongs.
It's called
AxImp
.C:\Program Files\Microsoft SDKs\Windows\v6.0A\bin\AxImp.exe
So basically, to generate a PIA DLL in your own customized namespace:
Register your OCX
regsvr32 abc.ocx
Generate a strong name key pair for you ocx by running
sn -k
Run TLBIMP and specify the desired namespace
tlbimp abc.ocx /primary /keyfile:abc.snk /out:abc.dll /namespace:MyNamespace
Run AXIMP on the ocx and use the
rcw
switch to use your own manully generated PIA DLL.aximp abc.ocx /source /rcw:abc.dll
That should do it.
There are however some problems with ancient TLBs being imported. I am not sure how to fix that yet.