【问题标题】:Working with strings, char array, c++ and assembly. Issue passing string to assembly使用字符串、字符数组、C++ 和程序集。将字符串传递给程序集的问题
【发布时间】:2013-11-29 19:21:00
【问题描述】:

我正在编写 C++ 和外部 asm 代码。我们需要使用外部 ASM 库。问题是,我很难将字符串从 c++ 端传递给 asm。我确定我在访问 asm 端的字符串时犯了一些错误。

我基本上是逐字阅读文本文件。然后我想将每个单词传递到 ASM 端并对其进行一些统计处理。

假设我从文件中检索了一个单词并将其存储在

string wordFromFile = "America";
processWord(wordFromFile, wordFromFile.size()) //processFromWord is the ASM side function

;;ASM SIDE
;;The doubt I have (first of all all) is how do I declare the arguments on the ASM SIDE
ProcessWordUpperCase PROC C, wordFile :BYTE, len :DWORD

OR

ProcessWordUpperCase PROC C, buffer :DWORD, len :DWORD  

我该怎么办?还有一件事,在函数中,我将按每个字母访问字符串。您对此有何建议?

【问题讨论】:

  • 澄清一下 - 您使用 MSVC++ 作为 C++ 编译器,使用 MASM 作为汇编程序?另外,这是 x86 还是 x64 程序集?
  • 我怀疑你能否在汇编程序中使用string object 做任何有用的事情。如果有的话,您应该使用 c_str 传递指针,但是您必须记住它是一个 constant 指针(因此您不能修改字符串)并且该指针也是临时的。
  • MSVC++、MASM 和 x86

标签: c++ string pointers assembly


【解决方案1】:

这是一个计算字符串长度的骨架,您可以在其中放置您的代码。

toupper.cpp

extern "C"
{
    int ProcessWordUpperCase(const char *wordFile, int arraySize);
};

int main(int argc, char*arg[])
{
    char t[100];
    int res;

    res = ProcessWordUpperCase(t, sizeof(t));

    std::string s = "myvalue";
    res = ProcessWordUpperCase(s.c_str(), s.length());

    return 0;
}

toupper.asm

.486
.model flat, C
option casemap :none

.code

ProcessWordUpperCase PROC, wordFile:PTR BYTE, arrayLen:DWORD

    LOCAL X:DWORD

    push        ebx  
    push        esi  
    push        edi  

    mov         edi, wordFile
    xor         eax, eax

    dec         edi
    dec         eax

@@StringLoop:
    inc         edi
    inc         eax
    cmp         byte ptr [edi], 0
    jne         @@StringLoop
    ; return length of string

    pop         edi  
    pop         esi  
    pop         ebx  

    ret  

ProcessWordUpperCase ENDP

END

【讨论】:

    【解决方案2】:

    获取函数骨架的一个简单技巧是告诉 VS 输出 ASM 文件。

    怎么做:

    用一个空函数创建一个新的源文件,其中包含你想要的原型 例如int foo(const char* s, int bar) { return *s + bar; }

    右键单击源文件并选择Properties->C/C++->Output Files->Assembler Output。 选择适合您的值。 构建并查看生成的 ASM 文件。 生成的 asm 文件包含一些可以通过使用该文件的编译标志来禁用的安全检查。

    【讨论】:

      【解决方案3】:

      从 C 端: 我会这样做:将字符串作为数组传递,以及数组中的许多字段。程序会将指向数组最开头的指针写入堆栈,因此如果要检索字符串中的第一个字符,只需将其称为

      mov eax, [adress of the pointer on stack]
      

      【讨论】:

      • 我试过这样做,但我从 char 数组中得到了奇怪的字符。我做了: char s[64]; for(int i=0;i
      • 对于c++ std::string(正如OP 要求的那样)[adress of the pointer on stack] 肯定不会指向字符数据!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-11-26
      • 2014-12-11
      • 1970-01-01
      • 1970-01-01
      • 2013-03-16
      • 2015-10-06
      • 1970-01-01
      相关资源
      最近更新 更多