I want to create an interface with API that can accept array of key-value pairs in COM. What is the best way to do that? I can think of sending SAFEARRAY of BSTR .Each BSTR can be considered as key-value pair . Logic of packing /unpacking key-values need to be added.
I wouldn't use BSTR for non-string uses -- it may save you a nanosecond but will eventually give problems if and when you need to extend or port your code. I'd just use a SAFEARRAY of variants with the keys at index 0, 2, 4... and the corresponding values at 1, 3, 5, ...
You can introduce an interface for a key-value pair and another one for the collection of such pairs.
You need to define "best". COM is -- despite its designers' best wishes -- a very heterogeneous platform. The nature of the the client (aka what language?) that you expect will interact with the object should heavily influence your choice.
Just two quick examples:
Being called from Classing ASP?
Your only tools are VARIANTS. Ok -- you're using ATL: Your only tools are either BSTRs or SAFEARRAYs of VARIANTS.Being called from C++?
You can use a custom data array (read up on [size_is]). Or even fixed-sized arrays if possible. It's TONS easier on both sides.
There are other considerations:
Are you writing the client? Then you want to make things easier on both sides.
Are you writing only the object? Then you probably want to make things easiest on the client, even if it's hardest on the server (why? Because you want the other party to be happy working with you, especially in a consulting or commercial environment -- don't look lazy!).
Also, is this a one-off object? Or will it be used in a number of circumstances in the future? In the former case, you might find that it really doesn't matter. In the latter, you will want to think it thoroughly.
If you post more details on your circumstances, we can probably give more specific guidance.