Listing 4

JNIEXPORT jstring JNICALL 
   Java_TradingSystemImpl_doGetQuote(JNIEnv * env, jobject me, jstring Stock)
{
    double quote = 0.0000;
    ITradeStock* pITradeStock = GetTradeStockRef();
    if ( pITradeStock ) 
    {
        // Convert the Java String, Stock, to a C++ char*
        const char* stockStr = (*env).GetStringUTFChars(Stock, 0);

        // Calling a COM interface, convert to a BSTR
        wchar_t stockWStr[32];
        mbstowcs(stockWStr, stockStr, strlen(stockStr));
        BSTR stock = SysAllocString(stockWStr);

        // Call the actual C++ implementation of this method
        pITradeStock->GetQuote(stock, &quote);
        SysFreeString(stock);
    }
    ReleaseTradeStockRef(pITradeStock);
    // Convert the quote returned from a double to a string 
    int  decimal, sign;
    char* pszQuote = _ecvt( quote, 4, &decimal, &sign );
    char szQuote[12];
    // We need to add the decimal point since _ecvt doen't
    strncpy( szQuote, pszQuote, decimal );
    szQuote[decimal] = NULL;
    strcat( szQuote, "." );
    strcat( szQuote, &pszQuote[decimal] );
    // Since Java is expecting a Java String object as the return to this 
    // method, we use the JNIEnv class to convert char* to 
    // a jstring object and return it
    return (*env).NewStringUTF(szQuote);
}