0 / 0 / 0
Регистрация: 03.06.2017
Сообщений: 11
1

При конвертировании из LPCSTR в std::string возвращаются иероглифы

10.08.2017, 16:20. Показов 532. Ответов 0

Author24 — интернет-сервис помощи студентам
Есть dll в которой определены функции конвертирования типов данных. Всё работает, за ислючением функции, возвращающих LP что-то там. В частности интересует std_string_TO_LPCSTR:
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
//dub1401.h
#pragma once
#include <string>
#include <Windows.h>
 
#ifdef FROMDLL
#define DECLSPEC _declspec(dllexport)
#else
#define DECLSPEC _declspec(dllimport)
 
#endif
 
namespace dub1401 {
 
    DECLSPEC std::string GetAdresFromEXE(std::string getname);
    DECLSPEC std::string bool_TO_std_string(bool value);
    DECLSPEC bool std_string_TO_bool(std::string value);
    DECLSPEC LPSTR std_string_TO_LPSTR(std::string value);
    DECLSPEC LPCSTR std_string_TO_LPCSTR(std::string value);
    DECLSPEC std::string LPSTR_TO_std_string(LPSTR value);
    DECLSPEC std::string LPCSTR_TO_std_string(LPCSTR value);
    DECLSPEC LPCWSTR std_string_TO_LPCWSTR(std::string value);
 
};
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
//Main.cpp
#define FROMDLL
 
#include "dub1401.h"
 
namespace dub1401 {
        
        //получает адрес исполняемого файла, принимает имя .exe файла для удаления из строки адреса
        std::string GetAdresFromEXE(std::string getname) {
        TCHAR buffer[2048];
        GetModuleFileName(NULL, buffer, 2048);
        std::string buf;
        buf = buffer;
        if (getname != "") {
            std::string::size_type pos = buf.find(getname);
            while (pos != std::string::npos)
            {
                buf.erase(pos, getname.size());
                pos = buf.find(getname, pos + 1);
            }
        }
 
        const char sym = '\\';
        for (std::string::iterator it = buf.begin(); it != buf.end(); ++it)
            if (*it == sym)
                it = buf.insert(++it, '\\');
        return buf.c_str();
    }
 
 
        //функции конвертирования типов данных
        std::string bool_TO_std_string(bool value) {
            if (value) { return "true"; }
            else { return "false"; }
        }
        
        bool std_string_TO_bool(std::string value) {
            if (value == "true") return true;
            else if (value == "false") return false;
            else return NULL;
        }
 
        LPSTR std_string_TO_LPSTR(std::string value) {
            return const_cast<char *>(value.c_str());
        }
 
        LPCSTR std_string_TO_LPCSTR(std::string value) {
            const char* str = value.c_str();;
            LPCSTR text = (LPCSTR)str;
            return text;
        }
 
        LPCWSTR std_string_TO_LPCWSTR(std::string value) {
            LPCWSTR text = (LPCWSTR)value.c_str();
            return text;
        }
 
        std::string LPSTR_TO_std_string(LPSTR value) {
            std::string buf;
            for (int i = 0; i <= sizeof(value); i++) {
                buf[i] = value[i];
            }
            return buf;
        }
 
        std::string LPCSTR_TO_std_string(LPCSTR value) {
            std::string buf;
            for (int i = 0; i <= sizeof(value); i++) {
                buf[i] = value[i];
            }
            return buf;
        }
}
И консольное приложение, использующее dll. Dll и приложение в Release x86.

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#pragma comment(lib, "dub1401.lib")
 
#include "dub1401.h"
#include <Windows.h>
#include <string>
#include <iostream>
 
using namespace std;
using namespace dub1401;
 
int main() {
    setlocale(LC_ALL, "");
    string str = GetAdresFromEXE("ConsoleApplication1.exe");
    cout << str << endl;
    str = "vdv";
    cout << bool_TO_std_string(true);
    LPCSTR vec = std_string_TO_LPCSTR(str);
    cout << vec << endl;
    MessageBox(NULL, vec, "ивчи ", MB_ICONERROR);
    system("pause");
    return 0;
}
0
Programming
Эксперт
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
10.08.2017, 16:20
Ответы с готовыми решениями:

Ошибка при конвертировании из string в int32
Выдаёт ошибку на этой строке: &quot;Входная строка имела неверный формат&quot;. Почему это происходит? При...

Пропадает текст String при конвертировании
Доброго утра всем,у меня вновь появился вопрос. У меня есть класс BaseUtils В нем такой...

ошибка error: cannot convert 'std::string {aka std::basic_string<char>}' to 'std::string* {aka std::basic_stri
на вод поступают 2 строки типа string. определить количество вхождений строки 2 в строку 1 ошибка...

Ошибка terminate called after throwing an instance of 'std::bad_alloc' при работе с типом std::string
Добрый вечер, при работе функции возникает ошибка terminate called after throwing an instance...

0
10.08.2017, 16:20
IT_Exp
Эксперт
87844 / 49110 / 22898
Регистрация: 17.06.2006
Сообщений: 92,604
10.08.2017, 16:20
Помогаю со студенческими работами здесь

Конфузы с русскими буквами при переводе из System::String^ в std::string
Использую такую конструкцию: string stdstr; for(int i=0;i&lt;sysstr-&gt;Length;++i) ...

Запрошено преобразование от ‘const std::string*’ к нескалярному типу ‘std::string’
private: std::string firstName; }; std::string ClientData::getFirstName() const{ ...

Перевод строк std::string, std::wstring в Unicode (String)
Собственно столкнулся с проблемой, как корректно перевести к примеру текст из Edit1-&gt;Text в...

String to LPCSTR
проблема такая (vc++ 2005) error C2664: 'CreateFileA' : cannot convert parameter 1 from...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
1
Ответ Создать тему
Опции темы

КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2024, CyberForum.ru