Модераторы: Daevaorn
  

Поиск:

Ответ в темуСоздание новой темы Создание опроса
> JavaScript to C++. The simplest thing, It really is 
:(
    Опции темы
Sasqatch
Дата 31.7.2004, 02:03 (ссылка)    |    (голосов: 0) Загрузка ... Загрузка ... Быстрая цитата Цитата


Unregistered











I'm sure that is very simple problem but i'm only beginner in C++, so i'll be very thankful for any advice.

I have some functions that manadge passing variables from JS to C and back and need convert JavaScript string to C/C++ char * data type (path to a file).
There is the special function JS_ValueToString which gets JS value (js string) convert it and returns a pointer that points to a null-terminated string. So a past several days i'm trying apply JavaScript programming knowledge but with no success smile.gif I've learned about pointers in C++ a little, but seems that this case differs from pointers to variables.

Below is the code i'm trying to finish:

Цитата

extern "C"
{
#include <TChar.h>
#include "mm_jsapi.h"

JSBool testFunc(JSContext *cx, JSObject *obj, unsigned int argc, jsval *argv, jsval *rval)
{
unsigned int leng;
unsigned short p;
char * my_str;

p = *JS_ValueToString(cx, argv[0], &leng);

my_str = ???

return JS_TRUE;
}
}


Just in case here is JS_ValueToString explanation from docs:

Цитата

unsigned short *JS_ValueToString()

Usage
unsigned short *JS_ValueToString(JSContext *cx, jsval v, unsigned int *pLength)

Description
This function extracts a function argument from a jsval structure, converts it to a string, if possible, and passes the converted value back to the caller.

Note: Do not modify the returned buffer pointer or you might corrupt the data structures of the JavaScript interpreter. To change the string, you must copy the characters into another buffer and create a new JavaScript string.

Arguments
JSContext *cx, jsval v, unsigned int *pLength

The cx argument is the opaque JSContext pointer that passes to the JavaScript function.
The v argument is the jsval structure from which the string is to be extracted.
The pLength argument is a pointer to an unsigned integer. This function sets *plength equal to the length of the string in bytes.

Returns
A pointer that points to a null-terminated string if successful or to a null value on failure. The calling routine must not free this string when it finishes.


THANK YOU FOR ANY ADVICE!
  Вверх
Дрон
Дата 31.7.2004, 21:32 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Java-ненавистник :)
****


Профиль
Группа: Участник Клуба
Сообщений: 3179
Регистрация: 29.12.2002
Где: Санкт-Петербург

Репутация: 10
Всего: 92



It looks strange that JS_ValueToString() function returns unsigned short* instead of char*. Are you sure that it doesn't return a unicode string?

In fact I've never worked with JS but I suppose this code should work correctly:
Цитата
extern "C"
{
     #include <TChar.h>
     #include "mm_jsapi.h"

     JSBool testFunc(JSContext *cx, JSObject *obj, unsigned int argc, jsval *argv, jsval *rval)
     {
          unsigned int leng;
          char *my_str;

          my_str = strdup((char*)JS_ValueToString(cx, argv[0], &leng));

          // here goes your code

          // and when "my_str" is no longer needed you must free the memory allocated by it
          free(my_str);

          return JS_TRUE;
     }
}
PS: Why don't you use Russian? smile.gif

Это сообщение отредактировал(а) Дрон - 31.7.2004, 21:44


--------------------
Да. Именно так.
PM   Вверх
  
Ответ в темуСоздание новой темы Создание опроса
Правила форума "С++:Общие вопросы"
Earnest Daevaorn

Добро пожаловать!

  • Черновик стандарта C++ (за октябрь 2005) можно скачать с этого сайта. Прямая ссылка на файл черновика(4.4мб).
  • Черновик стандарта C (за сентябрь 2005) можно скачать с этого сайта. Прямая ссылка на файл черновика (3.4мб).
  • Прежде чем задать вопрос, прочтите это и/или это!
  • Здесь хранится весь мировой запас ссылок на документы, связанные с C++ :)
  • Не брезгуйте пользоваться тегами [code=cpp][/code].
  • Пожалуйста, не просите написать за вас программы в этом разделе - для этого существует "Центр Помощи".
  • C++ FAQ

Если Вам понравилась атмосфера форума, заходите к нам чаще! С уважением, Earnest Daevaorn

 
0 Пользователей читают эту тему (0 Гостей и 0 Скрытых Пользователей)
0 Пользователей:
« Предыдущая тема | C/C++: Общие вопросы | Следующая тема »


 




[ Время генерации скрипта: 0.0845 ]   [ Использовано запросов: 22 ]   [ GZIP включён ]


Реклама на сайте     Информационное спонсорство

 
По вопросам размещения рекламы пишите на vladimir(sobaka)vingrad.ru
Отказ от ответственности     Powered by Invision Power Board(R) 1.3 © 2003  IPS, Inc.