<?xml version='1.0' encoding="utf-8"?>
      <rss version='2.0'>
      <channel>
      <title>Форум на Исходниках.RU</title>
      <link>https://forum.sources.ru</link>
      <description>Форум на Исходниках.RU</description>
      <generator>Форум на Исходниках.RU</generator>
  	
      <item>
        <guid isPermaLink='true'>https://forum.sources.ru/index.php?showtopic=411076&amp;view=findpost&amp;p=3735802</guid>
        <pubDate>Tue, 08 Aug 2017 15:57:53 +0000</pubDate>
        <title>конвертировать jstring to LCPWSTR</title>
        <link>https://forum.sources.ru/index.php?showtopic=411076&amp;view=findpost&amp;p=3735802</link>
        <description><![CDATA[korvin: <div class='tag-quote'><a class='tag-quote-link' href='https://forum.sources.ru/index.php?showtopic=411076&view=findpost&p=3735619'><span class='tag-quote-prefix'>Цитата</span></a> <span class='tag-quote__quote-info'>VisualProg &#064; <time class="tag-quote__quoted-time" datetime="2017-08-07T10:39:36+03:00">07.08.17, 07:39</time></span><div class='quote '>Скорее всего, я не правильно объяснился. Вот про что я имел ввиду.</div></div><br>
Мне из этого не понятно, что ты имел в виду.<br>
<br>
<div class='tag-quote'><a class='tag-quote-link' href='https://forum.sources.ru/index.php?showtopic=411076&view=findpost&p=3735619'><span class='tag-quote-prefix'>Цитата</span></a> <span class='tag-quote__quote-info'>VisualProg &#064; <time class="tag-quote__quoted-time" datetime="2017-08-07T07:39:36+00:00">07.08.17, 07:39</time></span><div class='quote '>Я просто не поверю что ява кодирует символы одним байтом)</div></div><br>
Какая ява? java.lang.String хранит массив char (Java&#39;вских char&#39;ов, не Сишных), которые двухбайтный UTF-16.<br>
JNI&#39;шный метод GetStringUTFChars, которым пользуется ТС, согласно документации на сайте, возврашает массив байтов (сишных char&#39;ов) UTF-8, которая мультибайтовая, т.е. символы (юникодные code point&#39;ы) там кодируются последовательностями от 1 до 6 байт, в зависимости от символа. Так, например, символы из ASCII кодируются одним байтом, символы кириллицы — двумя. В википедии есть же схема, ну. Сишный же wchar_t имеет размер (в винде) — 2 байта, следовательно массив UTF-8 char и массив UTF-16 wchar_t — не совместимы и кастить их нельзя, я же показал в какие последовательности байт преобразуются стринги, возьми UTF-8, подставь в <span class="tag-font" data-value="Courier" style="font-family:Courier">char* s1 = …</span>, и посмотри, что получится в <span class="tag-font" data-value="Courier" style="font-family:Courier">wchar_t* ws1 = (wchar_t*) ws1;</span><br>
<br>
<div class='tag-quote'><a class='tag-quote-link' href='https://forum.sources.ru/index.php?showtopic=411076&view=findpost&p=3735619'><span class='tag-quote-prefix'>Цитата</span></a> <span class='tag-quote__quote-info'>VisualProg &#064; <time class="tag-quote__quoted-time" datetime="2017-08-07T07:39:36+00:00">07.08.17, 07:39</time></span><div class='quote '>даже не подозревал что wchar_t 32 битный и использует 4 байта.</div></div><br>
Его размер зависит от платформы (ОС) и, наверное, ещё чего-то. На MSDN можно найти указание, что в винде он 16-битный.]]></description>
        <author>korvin</author>
        <category>Java</category>
      </item>
	
      <item>
        <guid isPermaLink='true'>https://forum.sources.ru/index.php?showtopic=411076&amp;view=findpost&amp;p=3735619</guid>
        <pubDate>Mon, 07 Aug 2017 07:39:36 +0000</pubDate>
        <title>конвертировать jstring to LCPWSTR</title>
        <link>https://forum.sources.ru/index.php?showtopic=411076&amp;view=findpost&amp;p=3735619</link>
        <description><![CDATA[VisualProg: <div class='tag-quote'><a class='tag-quote-link' href='https://forum.sources.ru/index.php?showtopic=411076&view=findpost&p=3735427'><span class='tag-quote-prefix'>Цитата</span></a> <span class='tag-quote__quote-info'>korvin &#064; <time class="tag-quote__quoted-time" datetime="2017-08-04T17:27:31+00:00">04.08.17, 17:27</time></span><div class='quote '>wprintf((const wchar_t*) s);</div></div><br>
Скорее всего, я не правильно объяснился. <a class='tag-url' href='http://ideone.com/GaV1I5' target='_blank'>Вот</a> про что я имел ввиду.<br>
<br>
<div class='tag-code'><span class='pre_code'></span><div class='code  code_collapsed ' title='Подсветка синтаксиса доступна зарегистрированным участникам Форума.' style=''><div><div><ol type="1"><div class="code_line">&nbsp;&nbsp; &nbsp;#include &#60;wchar.h&#62;</div><div class="code_line">&nbsp;&nbsp; &nbsp;#include &#60;stdio.h&#62;</div><div class="code_line">&nbsp;&nbsp; &nbsp; </div><div class="code_line">&nbsp;&nbsp; &nbsp;int main(void) {</div><div class="code_line">&nbsp;&nbsp; &nbsp; </div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;char* s1 = &quot;{text}H{text}e{text}l{text}l{text}o&quot;;</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;char* s2 = &quot;H{text}e{text}l{text}l{text}o{text}&quot;;</div><div class="code_line">&nbsp;&nbsp; &nbsp; </div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;wprintf((const wchar_t*) s1);</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;wprintf((const wchar_t*) s2);</div><div class="code_line">&nbsp;&nbsp; &nbsp; </div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;printf(&quot;\n--------\n&quot;);</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;const wchar_t* ws1 = (const wchar_t*) s1;</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;for (int i = 0; i &#60; 5; i++) {</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;printf(&quot;%d &quot;, ws1[i]);</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;}</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;printf(&quot;\n&quot;);</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;const wchar_t* ws2 = (const wchar_t*) s2;</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;for (int i = 0; i &#60; 5; i++) {</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;printf(&quot;%d &quot;, ws2[i]);</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;}</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;printf(&quot;\n--------\n&quot;);</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;return 0;</div><div class="code_line">&nbsp;&nbsp; &nbsp;}</div></ol></div></div></div></div><script>preloadCodeButtons('1');</script><br>
<br>
Я просто не поверю что ява кодирует символы одним байтом)<br>
И на этом примере вижу, что действительно ничего не получится, потому что я даже не подозревал что wchar_t 32 битный и использует 4 байта.]]></description>
        <author>VisualProg</author>
        <category>Java</category>
      </item>
	
      <item>
        <guid isPermaLink='true'>https://forum.sources.ru/index.php?showtopic=411076&amp;view=findpost&amp;p=3735427</guid>
        <pubDate>Fri, 04 Aug 2017 17:27:31 +0000</pubDate>
        <title>конвертировать jstring to LCPWSTR</title>
        <link>https://forum.sources.ru/index.php?showtopic=411076&amp;view=findpost&amp;p=3735427</link>
        <description><![CDATA[korvin: <div class='tag-quote'><a class='tag-quote-link' href='https://forum.sources.ru/index.php?showtopic=411076&view=findpost&p=3735224'><span class='tag-quote-prefix'>Цитата</span></a> <span class='tag-quote__quote-info'>VisualProg &#064; <time class="tag-quote__quoted-time" datetime="2017-08-03T07:36:46+00:00">03.08.17, 07:36</time></span><div class='quote '>А в чём может быть проблема? Хотите сказать, что в wchar_t байты с младшими и старшими разрядами перевёрнуты?</div></div><br>
Хочу сказать, что UTF-8 — мультибайтовая кодировка: один code point может быть представлен как одним, так и шестью байтами. Да что там говорить, даже если взять любую однобайтовую кодировку, каким образом, по-твоему, простой сишный тайпкаст должен преобразовать массив char&#39;ов в массив wchar_t&#39;ов, которые, в винде представляют двухбайтный UTF-16, а в *nix&#39;ах могут и UTF-32? Ну и byte-order, конечно, тоже.<br>
<br>
Например:<br>
<div class='tag-code'><span class='pre_code'></span><div class='code  code_collapsed ' title='Подсветка синтаксиса доступна зарегистрированным участникам Форума.' style=''><div><div><ol type="1"><div class="code_line">import java.nio.charset.Charset;</div><div class="code_line">import java.nio.charset.StandardCharsets;</div><div class="code_line">import java.util.Arrays;</div><div class="code_line">import java.util.function.Function;</div><div class="code_line">import java.util.stream.Stream;</div><div class="code_line">&nbsp;</div><div class="code_line">public final class Charsets {</div><div class="code_line">&nbsp;</div><div class="code_line">&nbsp;&nbsp; &nbsp;public static void main(String[] args) {</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;printBytes(&quot;Hello&quot;);</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;printBytes(&quot;Привет&quot;);</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;printBytes(&quot;こんにちは&quot;);</div><div class="code_line">&nbsp;&nbsp; &nbsp;}</div><div class="code_line">&nbsp;</div><div class="code_line">&nbsp;&nbsp; &nbsp;private static void printBytes(String s) {</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;Stream.of(StandardCharsets.US_ASCII, StandardCharsets.UTF_8, StandardCharsets.UTF_16)</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;.map(showBytes(s))</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;.forEach(System.out::println);</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;System.out.println();</div><div class="code_line">&nbsp;&nbsp; &nbsp;}</div><div class="code_line">&nbsp;</div><div class="code_line">&nbsp;&nbsp; &nbsp;private static Function&#60;Charset, String&#62; showBytes(String s) {</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;return cs -&#62; String.format(&quot;%s in %10s = %s&quot;, s, cs, Arrays.toString(s.getBytes(cs)));</div><div class="code_line">&nbsp;&nbsp; &nbsp;}</div><div class="code_line">}</div></ol></div></div></div></div><br>
получаем:<br>
<div class='tag-code'><span class='pre_code'></span><div class='code  code_collapsed ' title='Подсветка синтаксиса доступна зарегистрированным участникам Форума.' style=''><div><div><ol type="1"><div class="code_line">Hello in &nbsp; US-ASCII = [72, 101, 108, 108, 111]</div><div class="code_line">Hello in &nbsp; &nbsp; &nbsp;UTF-8 = [72, 101, 108, 108, 111]</div><div class="code_line">Hello in &nbsp; &nbsp; UTF-16 = [-2, -1, 0, 72, 0, 101, 0, 108, 0, 108, 0, 111]</div><div class="code_line">&nbsp;</div><div class="code_line">Привет in &nbsp; US-ASCII = [63, 63, 63, 63, 63, 63]</div><div class="code_line">Привет in &nbsp; &nbsp; &nbsp;UTF-8 = [-48, -97, -47, -128, -48, -72, -48, -78, -48, -75, -47, -126]</div><div class="code_line">Привет in &nbsp; &nbsp; UTF-16 = [-2, -1, 4, 31, 4, 64, 4, 56, 4, 50, 4, 53, 4, 66]</div><div class="code_line">&nbsp;</div><div class="code_line">こんにちは in &nbsp; US-ASCII = [63, 63, 63, 63, 63]</div><div class="code_line">こんにちは in &nbsp; &nbsp; &nbsp;UTF-8 = [-29, -127, -109, -29, -126, -109, -29, -127, -85, -29, -127, -95, -29, -127, -81]</div><div class="code_line">こんにちは in &nbsp; &nbsp; UTF-16 = [-2, -1, 48, 83, 48, -109, 48, 107, 48, 97, 48, 111]</div></ol></div></div></div></div><br>
<br>
Вот теперь представь, что у тебя <span class="tag-font" data-value="Courier" style="font-family:Courier">char* utf8 = [72, 101, 108, 108, 111]</span>, а ты его кастишь к <span class="tag-font" data-value="Courier" style="font-family:Courier">wchar_t* utf16 = (wchar_t*) utf8</span>, берёшь utf16[0] и получаешь, например (в зависимости от byte order), (72&lt;&lt;8)+101 = 18533. Какой это символ в Unicode? Дальше читаешь utf16[1], получаешь (108&lt;&lt;8)+108, потом utf16[2] -&gt; (111&lt;&lt;8)+0 (тот самый &#39;&#092;0&#39;), а дальше выход за пределы массива, UB, segfault и всё такое. Да, ты прав, что &#39;&#092;0&#39; пропускается, но причины другие.<br>
<br>
Вот попробуй:<br>
<div class='tag-code'><span class='pre_code'></span><div class='code  code_collapsed ' title='Подсветка синтаксиса доступна зарегистрированным участникам Форума.' style=''><div><div><ol type="1"><div class="code_line">#include &#60;wchar.h&#62;</div><div class="code_line">#include &#60;stdio.h&#62;</div><div class="code_line">&nbsp;</div><div class="code_line">int main(void) {</div><div class="code_line">&nbsp;&nbsp; &nbsp;char* s = &quot;Hello&quot;;</div><div class="code_line">&nbsp;&nbsp; &nbsp;printf(&quot;%s\n&quot;, s);</div><div class="code_line">&nbsp;&nbsp; &nbsp;wprintf((const wchar_t*) s);</div><div class="code_line">&nbsp;&nbsp; &nbsp;printf(&quot;\n--------\n&quot;);</div><div class="code_line">&nbsp;&nbsp; &nbsp;const wchar_t* ws = (const wchar_t*) s;</div><div class="code_line">&nbsp;&nbsp; &nbsp;for (int i = 0; i &#60; 5; i++) {</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;printf(&quot;%d &quot;, ws[i]);</div><div class="code_line">&nbsp;&nbsp; &nbsp;}</div><div class="code_line">&nbsp;&nbsp; &nbsp;printf(&quot;\n--------\n&quot;);</div><div class="code_line">&nbsp;&nbsp; &nbsp;return 0;</div><div class="code_line">}</div></ol></div></div></div></div><br>
<br>
Я удивлён, что у него вообще wprintf что-то напечатал внятное. <a class='tag-url' href='http://ideone.com/LM9oiV' target='_blank'>Ideone</a>, с 4-хбайтным wchar_t:<br>
<div class='tag-code'><span class='pre_code'></span><div class='code  code_collapsed ' title='Подсветка синтаксиса доступна зарегистрированным участникам Форума.' style=''><div><div><ol type="1"><div class="code_line">Hello</div><div class="code_line">&nbsp;</div><div class="code_line">--------</div><div class="code_line">1819043144 755630191 757935405 2960685 2122789 </div><div class="code_line">--------</div></ol></div></div></div></div>]]></description>
        <author>korvin</author>
        <category>Java</category>
      </item>
	
      <item>
        <guid isPermaLink='true'>https://forum.sources.ru/index.php?showtopic=411076&amp;view=findpost&amp;p=3735224</guid>
        <pubDate>Thu, 03 Aug 2017 07:36:46 +0000</pubDate>
        <title>конвертировать jstring to LCPWSTR</title>
        <link>https://forum.sources.ru/index.php?showtopic=411076&amp;view=findpost&amp;p=3735224</link>
        <description><![CDATA[VisualProg: <div class='tag-quote'><a class='tag-quote-link' href='https://forum.sources.ru/index.php?showtopic=411076&view=findpost&p=3734829'><span class='tag-quote-prefix'>Цитата</span></a> <span class='tag-quote__quote-info'>korvin &#064; <time class="tag-quote__quoted-time" datetime="2017-07-31T17:07:28+00:00">31.07.17, 17:07</time></span><div class='quote '>Я, может, чего-то не понимаю в C, но каким магическим образом, по-твоему, массив UTF-8 байт (char* ipstr), должен преобразоваться в массив wchar_t* обычным тайпкастом?</div></div><br>
<br>
А в чём может быть проблема? Хотите сказать, что в wchar_t байты с младшими и старшими разрядами перевёрнуты?]]></description>
        <author>VisualProg</author>
        <category>Java</category>
      </item>
	
      <item>
        <guid isPermaLink='true'>https://forum.sources.ru/index.php?showtopic=411076&amp;view=findpost&amp;p=3734829</guid>
        <pubDate>Mon, 31 Jul 2017 17:07:28 +0000</pubDate>
        <title>конвертировать jstring to LCPWSTR</title>
        <link>https://forum.sources.ru/index.php?showtopic=411076&amp;view=findpost&amp;p=3734829</link>
        <description><![CDATA[korvin: <div class='tag-quote'><a class='tag-quote-link' href='https://forum.sources.ru/index.php?showtopic=411076&view=findpost&p=3732424'><span class='tag-quote-prefix'>Цитата</span></a> <span class='tag-quote__quote-info'>Anka&#045;BOIN &#064; <time class="tag-quote__quoted-time" datetime="2017-07-12T13:01:27+00:00">12.07.17, 13:01</time></span><div class='quote '>jni прослойка libDllUse.с<br>
<div class='tag-code'><span class='pre_code'></span><div class='code  code_collapsed ' title='Подсветка синтаксиса доступна зарегистрированным участникам Форума.' style=''><div><div><ol type="1"><div class="code_line">static HINSTANCE mod;</div><div class="code_line">JNIEXPORT jint JNICALL Java_DllUse_connectDll</div><div class="code_line">(JNIEnv *env, jobject obj, jstring path)</div><div class="code_line">{ &nbsp; </div><div class="code_line">&nbsp;&nbsp; &nbsp;const char* ipstr=(*env)-&#62;GetStringUTFChars(env, path, NULL);</div><div class="code_line">&nbsp;</div><div class="code_line">&nbsp;&nbsp; &nbsp;wprintf((const wchar_t *)ipstr); &nbsp;// стр1</div><div class="code_line">&nbsp;</div><div class="code_line">&nbsp;&nbsp; &nbsp;mod=LoadLibrary((const wchar_t *)ipstr);</div><div class="code_line">&nbsp;&nbsp; &nbsp;(*env)-&#62;ReleaseStringUTFChars(env, path, ipstr1);</div><div class="code_line">&nbsp;&nbsp; &nbsp;if (mod == NULL) { &nbsp;return -1;}</div><div class="code_line">&nbsp;&nbsp; &nbsp;return 1;</div><div class="code_line">}</div></ol></div></div></div></div><br>
После вызова функция connectDl() возвращает -1, следовательно подключение не происходит. стр1 выводит: <br>
..путь..&#092;STF.dll_Разнообразная_Абракадабра</div></div><br>
Я, может, чего-то не понимаю в C, но каким магическим образом, по-твоему, массив UTF-8 байт (char* ipstr), должен преобразоваться в массив wchar_t* обычным тайпкастом?<br>
<br>
<a class='tag-url' href='https://maxammann.github.io/2015/01/11/c-utf8-to-wchar/' target='_blank'>https://maxammann.github.io/2015/01/11/c-utf8-to-wchar/</a> <br>
<br>
<span class="tag-color tag-color-named" data-value="mergepost" style="color: mergepost"><span class='tag-size' data-value='7' style='font-size:7pt;'>Добавлено <time class="tag-mergetime" datetime="2017-07-31T17:10:18+00:00">31.07.17, 17:10</time></span></span><br>
<div class='tag-quote'><a class='tag-quote-link' href='https://forum.sources.ru/index.php?showtopic=411076&view=findpost&p=3733025'><span class='tag-quote-prefix'>Цитата</span></a> <span class='tag-quote__quote-info'>VisualProg &#064; <time class="tag-quote__quoted-time" datetime="2017-07-17T14:12:25+00:00">17.07.17, 14:12</time></span><div class='quote '>В общем, попробую объяснить свою позицию. В яве строки (String) более правильные с точки зрения человека, то есть, имеется адрес начала строки, и длинна строки. В сях, ваш wchar_t* имеет адрес начала, но, не имеет длинны.<br>
<br>
Отсюда, чтобы узнать длину строки в яве, достаточно прочитать эту длину в области, недалеко от адреса начала массива данных (собственно, самой строки), как это сделано более подробно - это другой вопрос. Для того чтобы узнать длинну строки в сях, введено такое понятие как терминатор строки, суть в следующем, обращаемся по адресу начала строки, далее, смещаем курсор, читая по одному (или несколько) байту до тех пор, пока не натолкнёмся на &#092;0x00 терминатор (если читаем по несколько байт, скорее всего, достаточно того случая когда первый байт 0x00, но, могу ошибаться, и важно заполнить весь буфер &#092;0x00 терминаторами).<br>
<br>
Вот и получается - вы в памяти резервируете явой строку dirPath+&quot;libDllUse.dll&quot;, сишный код начинает искать конец этой строки, и пропускает курсор далеко за вашу строку, пока где то там, в памяти не наткнётся на &#092;0x00 терминатор.</div></div><br>
<br>
Судя по этой информации:<br>
<div class='tag-quote'><span class='tag-quote-prefix'>Цитата</span> <div class='quote '>UTF-8 strings are always terminated with the &#39;&#092;0&#39; character, whereas Unicode strings are not. To find out how many bytes are needed to represent a jstring in the UTF-8 format, JNI programmers can either call the ANSI C function strlen on the result of GetStringUTFChars, or call the JNI function GetStringUTFLength on the jstring reference directly.</div></div><br>
— <a class='tag-url' href='https://stackoverflow.com/a/16700206' target='_blank'>https://stackoverflow.com/a/16700206</a><br>
дело не в &#39;&#092;0&#39;.]]></description>
        <author>korvin</author>
        <category>Java</category>
      </item>
	
      <item>
        <guid isPermaLink='true'>https://forum.sources.ru/index.php?showtopic=411076&amp;view=findpost&amp;p=3733025</guid>
        <pubDate>Mon, 17 Jul 2017 14:12:25 +0000</pubDate>
        <title>конвертировать jstring to LCPWSTR</title>
        <link>https://forum.sources.ru/index.php?showtopic=411076&amp;view=findpost&amp;p=3733025</link>
        <description><![CDATA[VisualProg: <div class='tag-quote'><a class='tag-quote-link' href='https://forum.sources.ru/index.php?showtopic=411076&view=findpost&p=3732424'><span class='tag-quote-prefix'>Цитата</span></a> <span class='tag-quote__quote-info'>Anka&#045;BOIN &#064; <time class="tag-quote__quoted-time" datetime="2017-07-12T13:01:27+00:00">12.07.17, 13:01</time></span><div class='quote '>public static int connectDl(){<br>
        return new DllUse().connectDll(dirPath+&quot;STF.dll&quot;);<br>
    }</div></div><br>
<br>
Пробовали в си-стиле делать?<br>
<br>
Для wchar_t*<br>
<div class='tag-code'><span class='pre_code'></span><div class='code  code_collapsed ' title='Подсветка синтаксиса доступна зарегистрированным участникам Форума.' style=''><div><div><ol type="1"><div class="code_line">public static int connectDl(){</div><div class="code_line">&nbsp;&nbsp; &nbsp;return new DllUse().connectDll(dirPath+&quot;STF.dll{text}x00&quot;);</div><div class="code_line">}</div></ol></div></div></div></div> <br>
<br>
<span class="tag-color tag-color-named" data-value="mergepost" style="color: mergepost"><span class='tag-size' data-value='7' style='font-size:7pt;'>Добавлено <time class="tag-mergetime" datetime="2017-07-17T14:25:12+00:00">17.07.17, 14:25</time></span></span><br>
В общем, попробую объяснить свою позицию. В яве строки (String) более правильные с точки зрения человека, то есть, имеется адрес начала строки, и длинна строки. В сях, ваш wchar_t* имеет адрес начала, но, не имеет длинны.<br>
<br>
Отсюда, чтобы узнать длину строки в яве, достаточно прочитать эту длину в области, недалеко от адреса начала массива данных (собственно, самой строки), как это сделано более подробно - это другой вопрос. Для того чтобы узнать длинну строки в сях, введено такое понятие как <a class='tag-url' href='https://ru.wikipedia.org/wiki/%D0%9D%D1%83%D0%BB%D1%8C-%D1%82%D0%B5%D1%80%D0%BC%D0%B8%D0%BD%D0%B8%D1%80%D0%BE%D0%B2%D0%B0%D0%BD%D0%BD%D0%B0%D1%8F_%D1%81%D1%82%D1%80%D0%BE%D0%BA%D0%B0' target='_blank'>терминатор строки</a>, суть в следующем, обращаемся по адресу начала строки, далее, смещаем курсор, читая по одному (или несколько) байту до тех пор, пока не натолкнёмся на &#092;0x00 терминатор (если читаем по несколько байт, скорее всего, достаточно того случая когда первый байт 0x00, но, могу ошибаться, и важно заполнить весь буфер &#092;0x00 терминаторами).<br>
<br>
Вот и получается - вы в памяти резервируете явой строку <em class='tag-i'>dirPath+&quot;libDllUse.dll&quot;</em>, сишный код начинает искать конец этой строки, и пропускает курсор далеко за вашу строку, пока где то там, в памяти не наткнётся на &#092;0x00 терминатор.]]></description>
        <author>VisualProg</author>
        <category>Java</category>
      </item>
	
      <item>
        <guid isPermaLink='true'>https://forum.sources.ru/index.php?showtopic=411076&amp;view=findpost&amp;p=3732424</guid>
        <pubDate>Wed, 12 Jul 2017 13:01:27 +0000</pubDate>
        <title>конвертировать jstring to LCPWSTR</title>
        <link>https://forum.sources.ru/index.php?showtopic=411076&amp;view=findpost&amp;p=3732424</link>
        <description><![CDATA[Anka-BOIN: Доброго времени суток.<br>
Ситуация следующая. Существует сторонняя dll-библиотека без доступа к исходникам(STF.dll) и программа на java. Необходимо использовать функции библиотеки в программе с помощью JNI(обязательное условие).<br>
Сейчас подключение выглядит так.<br>
<br>
java:<br>
<div class='tag-code'><span class='pre_code'></span><div class='code  code_collapsed ' title='Подсветка синтаксиса доступна зарегистрированным участникам Форума.' style=''><div><div><ol type="1"><div class="code_line">public class DllUse {</div><div class="code_line">&nbsp;&nbsp; &nbsp;private static String dirPath;</div><div class="code_line">&nbsp;&nbsp; &nbsp;static{</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;try{ &nbsp;</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;dirPath = ..путь..; ///путь до библиотеки</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;System.load(dirPath+&quot;libDllUse.dll&quot;); &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;} catch(Exception ex) {}</div><div class="code_line">&nbsp;&nbsp; &nbsp;}</div><div class="code_line">&nbsp;</div><div class="code_line">&nbsp;&nbsp; &nbsp;public static int connectDl(){</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;return new DllUse().connectDll(dirPath+&quot;STF.dll&quot;);</div><div class="code_line">&nbsp;&nbsp; &nbsp;}</div><div class="code_line">&nbsp;&nbsp; &nbsp;private native int connectDll(String path);</div><div class="code_line">}</div></ol></div></div></div></div><br>
<br>
jni прослойка libDllUse.с<br>
<div class='tag-code'><span class='pre_code'></span><div class='code  code_collapsed ' title='Подсветка синтаксиса доступна зарегистрированным участникам Форума.' style=''><div><div><ol type="1"><div class="code_line">static HINSTANCE mod;</div><div class="code_line">JNIEXPORT jint JNICALL Java_DllUse_connectDll</div><div class="code_line">(JNIEnv *env, jobject obj, jstring path)</div><div class="code_line">{ &nbsp; </div><div class="code_line">&nbsp;&nbsp; &nbsp;const char* ipstr=(*env)-&#62;GetStringUTFChars(env, path, NULL);</div><div class="code_line">&nbsp;</div><div class="code_line">&nbsp;&nbsp; &nbsp;wprintf((const wchar_t *)ipstr); &nbsp;//стр1</div><div class="code_line">&nbsp;</div><div class="code_line">&nbsp;&nbsp; &nbsp;mod=LoadLibrary((const wchar_t *)ipstr);</div><div class="code_line">&nbsp;&nbsp; &nbsp;(*env)-&#62;ReleaseStringUTFChars(env, path, ipstr1);</div><div class="code_line">&nbsp;&nbsp; &nbsp;if (mod == NULL) { &nbsp;return -1;}</div><div class="code_line">&nbsp;&nbsp; &nbsp;return 1;</div><div class="code_line">}</div></ol></div></div></div></div><br>
После вызова функция connectDl() возвращает -1, следовательно подключение не происходит. стр1 выводит: <br>
..путь..&#092;STF.dll_Разнообразная_Абракадабра<br>
<br>
Как скормить jstring path функции <div class='tag-code'><span class='pre_code'></span><div class='code  code_collapsed ' title='Подсветка синтаксиса доступна зарегистрированным участникам Форума.' style=''><div><div><ol type="1"><div class="code_line">HMODULE WINAPI LoadLibrary(_In_ LPCTSTR lpFileName);</div></ol></div></div></div></div>?<br>
Или что ещё можно придумать в рамках заданных условий?<br>
Буду рада любой помощи.<br>
<br>
PS.<br>
<div class='tag-code'><span class='pre_code'></span><div class='code  code_collapsed ' title='Подсветка синтаксиса доступна зарегистрированным участникам Форума.' style=''><div><div><ol type="1"><div class="code_line">LoadLibrary(TEXT(&quot;..путь..\STF.dll&quot;));</div></ol></div></div></div></div> отлично работает, но путь до библиотек задается в java-программе (обязательное условие);]]></description>
        <author>Anka-BOIN</author>
        <category>Java</category>
      </item>
	
      </channel>
      </rss>
	